#!/usr/bin/env python
#coding: utf-8

#
# need to get usr/lib/python2.3/xml/sax/saxext.py file or the library containing that info
# inorder for this to continue working on OS X 10.4 - Try getting it off linux computers.s
#

import sys
import os
import os.path
import codecs  #this is important when dealing with unicode!!!
#import re 
#don't change the next line...or you will die
enc, dec = codecs.lookup('utf-8')[:2]

from xparser import XElementParser
from xelement import XElement
from html_element_stack import html_element_stack
import re
import time
import glob #to check if a file exists

#################################
#           GLOBALS		#
#################################
global HOMEPAGE 	#HOMEPAGE is a global variable used through out the translation.  This is used to link back to the 'home' page of the website/application.
			#The value of HOMEPAGE should never be changed.
global FOLDER		#FOLDER is the folder which the website will be generated to.

global FILENAMES 	#FILENAMES is a dictionary of the manuscript files which the translator will create upon running.  These files are mapped to a specific letter
			#per design of the application specifications.  The files generated for the menuscripts are actually broken up into multiple pages
			# so the actual filename is split at the '.' and a '_<page_number>' is added so the actual file name = "<filename before '.'>_<page number>.html"
			
global CURRENT_FILE	#CURRENT_FILE is a virtual file which controls the output of all files 'generated' (NOT COPIED) by this program

global file_count	#FILE_COUNT is used to count the number of files output by the program

global SITEFILES	#SITEFILES is a dictionary that hold all the filenames of NON-HTML files which the website will need to function.  This includes picture files and javascript files.
			#any future needed files of this nature should be added to this list.

global MAINFILES	#MAINFILES is a dictionary of all STATIC HTML files that need to be copied to the working website directory.  These files are coppied from the local directory 
			#where the program is installed and put into the root website directory

global HTML_STACK	# HTML_STACK is a global used to keep track of open tags in the CURRENT_FILE incase we come accross a page marker.
			# this allows us to close a page and reopen the next while keeping the look of the canon the same as it crosses
			# from one page to the next

global CURRENT_PAGE	#CURRENT_PAGE holds the value of the current page so other classed can access/set it ... THIS IS USED WHEN: building the lpdb database that maps canon numbers to their pages

global PREVIOUS_PAGE	#PREVIOUS_PAGE holds the value of the previous page so other classed can access/set it ...THIS IS USED WHEN: building the lpdb database that maps canon numbers to their pages

global CURRENT_MS_KEY	#CURRENT_MS_KEY hold the value of the current mansucript in question.  Usually set when looking at individual canons and access to the lpdb database 
			#that maps canon numbers to their pages

global MS_LPDB		#MS_LPDB MANSUCRIPT LINE TO PAGE DATABASE: used to ask what page a canon number is on

global TRANS_LPDB	#TRANS_LPDB MANUSCRIPT LINE TO PAGE DATBASE: used to ask what page a canon number is on

global MS_PG_MAP	#MS_PG_MAP is a virtual page tool used to output the page navigation control for the mansucript pages in the web application

global TRANS_PG_MAP	#TRANS_PG_MAP is a virtual page too used to output the page navigation control for the translation pages in the web application

#################################
#          SET GLOBALS		#
#################################

# NOTE the GLOBAL CURRENT FILE has been inited below the 'current_file' class

HOMEPAGE = "index.html"
#FOLDER = "/var/www/localhost/htdocs/OE/"
#FOLDER = "/Volumes/THUMBDRIVE/OE/OE/testsite/"
#FOLDER = "/Volumes/THUMBDRIVE/oe_temp/"
#FOLDER = "<generated files path>" 
#FOLDER = raw_input( "Enter the Path where the site will be generated (or help):" )
#FOLDER = "/cygdrive/c/PROJECTS/OEP_SITE/"
#FOLDER='/homes/users/cs/students/2005/cgrubbs/public_html/OEP/'
FOLDER = "/Users/christophergrubbs/Documents/testOEPsite/"
#FOLDER = "/home/matt/OE_release_1/OE/testsite/"
FILENAMES = {'D':"CORP201.html", 'C':"CORP265.html", 'S':"CORP190.html", 'B':"BX8558.html", 'Y':"LAUD482.html", 'X':"JUNIUS.html", 'N':"COTTIBA3.html"}

  # KEYS and what files they map too ... translations get tricky
  # NEED TO GET WITH ALLEN AND WRITE THE TECHNICAL SPECS FOR 
  # TRANSLATIONS RULES FOR THE GET_TRANSLATION FUNCTIONS FOR FOR FUTURE 
  # CHANGES, UPDATE, AND NEW FEATURES OTHERS MIGHT ADD 
  #
  #  KEY | FILENAME
  #--------------------
  #   D  | TOEH201.xml
  #   C  | TOEH265.xml
  #   S  | TOEI190.xml
  #   S2 | TOEP190.xml
  #   S3 | TSBOC190.xml
  #   S4 | TCTH190.xml
  #   B  | TCTH8558.xml
  #   B2 | TOEH8558.xml
  #   Y  | TOEP482.xml
  #   Y2 | TOEI482.xml
  #   Y3 | TSBOC482.xml
  #   Y4 | TCTH482.xml
  #   X  | TSBOC121.xml
  #   X2 | TOEP121.xml
  #   X3 | TOEI121.xml
  #   N  | TOEHCTA3.xml

TRANS_FILENAMES = {'D': 'TOEH201.html', 'C':'TOEH265.html', 'S':'TOEI190.html' , 'S2':'TOEP190.html', 'S3':'TSBOC190.html', 'S4':'TCTH190.html', 'B':'TCTH8558.html', 'B2':'TOEH8558.html', 'Y':'TOEP482.html', 'Y2':'TOEI482.html', 'Y3':'TSBOC482.html', 'Y4':'TCTH482.html', 'X':'TSBOC121.html', 'X2':'TOEP121.html', 'X3':'TOEI121.html', 'N':'TOEHCTA3.html'}

#file_count is a global value used to keep track of the total number of files output by the translator
#This value is incremented by 1 everytime a file is written.
file_count =0

#site files related to the generated files' performance and display
SITEFILES = ['wz_tooltip.js', 'moving_table.js', 'main.css']
picsdir = os.getcwd() + '/sitefiles/pics/'
for root, dirs, files in os.walk(picsdir):
	for file in files:
		filelower = file.lower()
		if filelower.endswith('.jpg') or filelower.endswith('.png') or filelower.endswith('.gif'):
			SITEFILES.append('pics/' + file)

#future designs may want to incorporate these files into an easy to generate format(html files only) for generating the menus
 #all site html files and their related non-generated content
MAINFILES = ['index.html', 'guide.html', 'biblio.html', 'credits.html', 'history.html', 'glossary.html', 'txhdoep.html', 'txhdoei.html', 'txhdsbc.html', 'txhdcth.html', 'txhdoeh.html', 'char2sbc.html', 'char3cth.html', 'char3oeh.html', 'char3oei.html', 'char3oep.html', 'char3sbc.html', 'char4cth.html', 'char4oeh.html', 'char4oei.html', 'char4oep.html', 'char4sbc.html', 'char5cth.html', 'char5oeh.html', 'char5oei.html', 'char5oep.html', 'char5sbc.html', 'mshd201.html', 'msch201.html', 'mshd265.html', 'msch265.html', 'msch482.html', 'mshd8558.html', 'mschbx85.html', 'mshd121.html', 'mshdcta3.html', 'msch190.html', 'mschcta3.html', 'msch121.html', 'mshd482.html', 'mshd190.html', 'animals.html', 'death.html', 'eucharis.html', 'children.html', 'food.html', 'emotions.html', 'murder.html', 'paganism.html', 'theft.html', 'sexsame.html', 'sexmafe.html', 'sexself.html', 'ms190images.html', 'ms201images.html', 'ms265images.html', '1990PREF.pdf']
#MAINFILES = ['index.html', 'guide.html', 'biblio.html', 'credits.html', 'history.html', 'glossary.html', 'txhdoep.html', 'txhdoei.html', 'txhdsbc.html', 'txhdcth.html', 'txhdoeh.html', 'mshd201.html', 'mshd265.html', 'mshd8558.html', 'mshd121.html', 'mshdcta3.html', 'mshd482.html', 'mshd190.html', 'animals.html', 'death.html', 'eucharis.html', 'children.html', 'food.html', 'emotions.html', 'murder.html', 'paganism.html', 'theft.html', 'sexsame.html', 'sexmafe.html', 'sexself.html' ]
 
HTML_STACK = html_element_stack()
CURRENT_PAGE = ""
PREVIOUS_PAGE = ""

#################################
#       CONFIG.XML SECTION		#
#################################

#classes for config.xml's items
class OEPConfig(XElement): pass
class ConfigItem(XElement):
	def getType(self):
		return self.getAttributes().getAll('type')[0]

#load config.xml into dictionary. YAML might be a better choice for this -cg
configxp = XElementParser({'OEPConfig':OEPConfig, 'ConfigItem':ConfigItem})
configData = configxp.process('config.xml').getChildren()
configMap = {}
for e in configData:
	configMap[e.getType()] = e.getText().strip()

configMap['STATIC_FOOTER'] = configMap['STATIC_FOOTER'].replace('&amp;copy;', '&copy;')
    
#hack for now, since menus on manuscript pages have a different div name than the others
#configMap['MSMENU_OPEN'] = '<div id="menu">' + configMap['MSMENU']
#configMap['MSMENU'] = '<div id="menu_container">' + configMap['MSMENU']

#cgrubbs hack to map citation numbers to folio numbers
citationDict = {}
    
#\\        //  __    ,,,    _  _  __  __   _  _   ,,,,
# \\  /\  //  //\\   ||`)  |\\||    ][    |\\||  // ...
#  \\//\\//  //==\\  ||\\  ||\||  __][__  ||\||  \\__||
# DONT CHANGE ANYTHING BELOW THIS LINE UNKLESS YOU KNOW WHAT YOU'RE DOING.
#

# CLASS CURRENT_FILE
#	this class acts as a virtual file and is used to control all 'generated' (NOT COPIED) file output
#	THIS IS IMPLEMENTED IN A GLOBAL VARIABLE called 'CURRENT_FILE' and the class needs access to GLOBALS 
#	in the system and therefore CAN NOT be moved to an external file with out finding a way to share the
#	globals
#
class current_file:
  def __init__(self):
    global MENU
    self.DEBUG = False
    self.text =""
    self.current_page =""
    self.filename = ""
    self.num_of_files_written = 0
    self.write_folder = FOLDER
    self.name_set = False
    self._type = '' 
    
  #set current file to write page too  
  def set_filename(self, general_html_filename, page_number):
    #
    # expect general_html_file to be <filename>.<html>
    #
    self.current_page = page_number
    name = general_html_filename.split('.')
    self.filename = name[0]+"_"+page_number+"."+name[1]
    self.name_set = True
    
  #add's text to self.text which will be written to the file
  def add_text(self, text):
    self.text += text

  #returns text...for debug purposes
  def get_text(self):
    return self.text

  #returns the current filename for debug purposes
  def get_filename(self):
    return self.filename

  #writes the file to the current folder specified in the globals
  #then clear filename and text
  def write(self):
    if self.name_set:
      if self.DEBUG:
        #print "*******************************************************"
        print "\tWriting "+self.write_folder+self.filename+"..."
      file = open(self.write_folder+self.filename, "w")
      file.write(self.text)
      file.close()
      if self.DEBUG:
        print "\t - Done!"
        #print "*******************************************************"
      self.num_of_files_written += 1
      self.filename = ""
      self.text= ""
      self.current_page = ""
      self.name_set = False
    else:
      print "WRITE FAILED BECAUSE FILE NAME WAS NOT SET BEFORE WRITE ATTEMPT!!!"

  def text_open(self, database):
    global CURRENT_MS_KEY, TRANS_PG_MAP, MS_PG_MAP, FILENAMES
    #temp = self.add_MS_header( database.get_MS_name( CURRENT_MS_KEY ) )
    #print dir(database)
    #print CURRENT_MS_KEY
    #print  self.get_MS_header( database.get_MS_name( CURRENT_MS_KEY ) )
    #temp = "hello"
    self.text = configMap['MSHEADER'] + self.get_MS_menu()
    if self._type == 'manuscript':
      self.text += self.get_MS_header(database.get_MS_name(CURRENT_MS_KEY, False))
      self.text += MS_PG_MAP.get_page_controls_top(CURRENT_MS_KEY, self.current_page, FILENAMES[ CURRENT_MS_KEY ])
    elif self._type == 'translation':
      print "TRANSLATION DETECTED!"
      self.text += self.get_MS_header(database.get_MS_name(CURRENT_MS_KEY, True))
      self.text += TRANS_PG_MAP.get_page_controls_top(CURRENT_MS_KEY, self.current_page, TRANS_FILENAMES[ CURRENT_MS_KEY ])
    if self._type == 'translation':
      self.text += configMap['MSCONTAINERTRANSLATION']
    else:
      self.text += configMap['MSCONTAINER']

  def text_close(self, database):
    self.text += """
     			  <div class="bottom_page_spacer">&nbsp;</div>
                        </td>
		      </tr>
                    </table>
		  </td>
		</tr>
	      </table>
	    </td>
	  </tr>
        </table>
      </div>      
    </center>    
    <div class="bottom_page_container">
    """
    if self._type == 'manuscript':
      self.text += MS_PG_MAP.get_page_controls_bottom(CURRENT_MS_KEY, self.current_page, FILENAMES[ CURRENT_MS_KEY ])
      self.text += self.get_MS_header_bottom(database.get_MS_name(CURRENT_MS_KEY)) 
    elif self._type == 'translation':
      self.text += TRANS_PG_MAP.get_page_controls_bottom(CURRENT_MS_KEY, self.current_page, TRANS_FILENAMES[ CURRENT_MS_KEY ])
      self.text += self.get_MS_header_bottom(database.get_MS_name(CURRENT_MS_KEY, True))
    self.text += """
    <div id="bottom_page_info">
      <center> 
         Copyright &copy; 2006 
	 <a href="http://www.luc.edu/faculty/afrantz/" title="This will open the home page of Allen J. Frantzen in a new window." target="_blank" style="color: #626C9B; text-decoration: none">Allen J. Frantzen</a>
	 - All rights reserved
	 <br/>
	 <a id="homelink" title="Click here to go back to the main page." href="index.html">The Anglo-Saxon Penitentials: <div>A cultural database</div></a>
	 was programmed by <a href="mailto:msellar@luc.edu" style="color: #626C9B; text-decoration: none" title="Contact Matt Sellars">Matt Sellars</a>
      </center>
    </div>
    </div>
    <script language="JavaScript" type="text/javascript" src="moving_table.js"></script>
    <script language="JavaScript" type="text/javascript" src="wz_tooltip.js"></script>  
  </body>
</html>
    """
  def set_type(self, type):
    self._type = type

  def get_MS_header(self, MS_name):
    if CURRENT_MS_KEY.find('S') != -1 or CURRENT_MS_KEY.find('D') != -1 or CURRENT_MS_KEY.find('C') != -1:
    	return """<div id="header_top"><span>"""+MS_name+" p. "+self.current_page+"""</span></div>"""
    else:
        return """<div id="header_top"><span>"""+MS_name+" fol. "+self.current_page+"""</span></div>"""        
  
  def get_MS_header_bottom(self, MS_name):
    if CURRENT_MS_KEY.find('S') != -1 or CURRENT_MS_KEY.find('D') != -1 or CURRENT_MS_KEY.find('C') != -1:
    	return """<div id="header_bottom"><span>"""+MS_name+" p. "+self.current_page+"""</span></div>"""
    else:
        return """<div id="header_bottom"><span>"""+MS_name+" fol. "+self.current_page+"""</span></div>""" 
  
  def get_MS_menu(self):
    return '<div id="menu_container">' + configMap['MSMENU']
   
  def is_name_set(self):
    return self.name_set
  
  def get_files_written(self):
    return self.num_of_files_written

  def turn_on_debug(self):
    self.DEBUG = True

  def turn_off_debug(self):
    self.DEBUG = False

  def get_current_page(self):
    return self.current_page
#
# File control vars for splitting the ms into pages
#   see above class
#
# SET LAST GLOBAL!
#
CURRENT_FILE = current_file()

class page_map:
  def __init__(self, translation=False):
    # database of pages and how they map for each manuscript
    # we build the page map while we build the line page database known as the line_page_db global variable is MS_LPDB
    # ms_key and current page# are the the keys
    # database data structure is { ms_key:{ current_page#: [previous_page#, next_page#] } }    
    #self.database = {'D':{}}
    self.translation = translation
    if self.translation:
      self.database = { 'D':{}, 'C':{}, 'S':{}, 'S2':{}, 'S3':{}, 'S4':{}, 'B':{}, 'B2':{}, 'Y':{}, 'X':{}, 'X2':{}, 'X3':{}, 'N':{}, 'Y2':{}, 'Y3':{}, 'Y4':{}}
    else:
      self.database = {'D':{}, 'C':{}, 'S':{}, 'Y':{}, 'B':{}, 'X':{}, 'N':{}}

  def update_page(self, ms_key, curr, prev=None, next=None):
    
    temp_dict = {curr : [prev, next]}
    #print "Update called with: "+ str( temp_dict )
    #if self.database[ ms_key ].has_key( curr ): #if we alread have the page mapped...remove it and update it
      #temp = self.database[ ms_key]
    #print "translation setting: "+str( self.translation )
    #print "page_map (DEBUG): "+str( self.database )  
    self.database[ ms_key ].update(temp_dict)

  def print_page_map(self):
  
   #print self.database
    for key in self.database:
      self.print_ms_page_map(key)
      #print "| -- MS --|-- PAGE --|-- PREV --|-- NEXT --|"
      #pages = self.database[key].keys()
      #pages.sort()
      #for page in pages:
      #  print "| -- "+key+" --|-- "+page+" --|-- "+str( self.database[key][page][0] )+" --|-- "+str( self.database[key][page][1] )+" --|"
	
  def get_first_page(self, ms_key):
    pages = self.database[ms_key].keys()
    pages.sort()
    if self.database[ ms_key ][pages[0]][0] == None or self.database[ ms_key ][pages[0]][0] == "":
      return pages[0]
    else:
      for page in pages:
        #print "CHECKING "+page+" FOR FIRST PAGE..."
	#print "\t next page is "+ str( self.database[ ms_key ][page][0] )
        if self.database[ ms_key ][page][0] == None or self.database[ ms_key ][page][0] == "": #if there is no previous page then that is the first page
	  return page

  def get_next_page(self, ms_key, current_page):
    return self.database[ms_key][current_page][1]
    
  def get_previous_page(self , ms_key, current_page):
    return self.database[ms_key][current_page][0]
    
  def get_last_page(self, ms_key):
    pages = self.database[ms_key].keys()
    pages.sort()
    if self.database[ ms_key ][ pages[len(pages)-1] ][1] == None or self.database[ ms_key ][ pages[len(pages)-1] ][1] == "":
      return pages[ len(pages)-1 ]
    else:
      for page in pages:
        #print "CHECKING "+page+" FOR LAST PAGE..."
	#print "\t next page is "+str( self.database[ ms_key ][ page ][1] )
        if self.database[ ms_key ][ page ][1] == None or self.database[ ms_key ][ page ][1] == "": #if there is no previous page then that is the first page
	  return page
  
  #render the HTML page controlls
  def get_page_controls_top(self, ms_key, current_page, html_filename):    
    #if self.translation:
    #  print "TRANSLATION IS AWESOME!"
    #  for x in self.database[ms_key]:
    #    print x
    print  'get_page_controls_top (DEBUG) ms_key: '+str(ms_key)
    print  'get_page_controls_top (DEBUG) current_page: '+str(current_page)
    name = html_filename.split('.')  
    first_page = self.get_first_page(ms_key)
    previous_page = self.get_previous_page(ms_key, current_page)
    next_page = self.get_next_page(ms_key, current_page)
    last_page = self.get_last_page(ms_key)
    drop_down = ""
    print "FIRST PAGE: "+str(last_page)
    print "CURRENT_PAGE: "+str(current_page)
    print "LAST PAGE: "+str(last_page)
    controls = configMap['MSPAGECONTROLS_TOP']
    if current_page == first_page and not current_page == last_page:
      controls = controls % ("""
		     <td align="center"><a class="pg_nav" title="The current page"><img src="pics/OE_page_Nav_first_inactive.png"/></a></td>
		     <td align="center"><a class="pg_nav" title="No previous page"><img src="pics/OE_page_Nav_prev_inactive.png"/></a></td>
		     <td class="page_drop_down" align="center">Fol: """+self.get_page_drop_down(ms_key, current_page, html_filename)+"""</td>
		     <td align="center"><a class="pg_nav" title="Next page of this manuscript" href=\""""+name[0]+"_"+next_page+"."+name[1]+"""\"><img border="0" src="pics/OE_page_Nav_next.png"/></a></td>
		     <td align="center"><a class="pg_nav" title="Last page of this manuscript" href=\""""+name[0]+"_"+last_page+"."+name[1]+"""\"><img border="0" src="pics/OE_page_Nav_last.png"/></a></td>
             """)
    elif current_page == last_page and not current_page == first_page:
      controls = controls % ("""
		     <td align="center"><a class="pg_nav" title="First page of this manuscript" href=\""""+name[0]+"_"+first_page+"."+name[1]+"""\"><img border="0" src="pics/OE_page_Nav_first.png"/></a></td>
		     <td align="center"><a class="pg_nav" title="Previous page of this manuscript" href=\""""+name[0]+"_"+previous_page+"."+name[1]+"""\"><img border="0" src="pics/OE_page_Nav_prev.png"/></a></td>
		     <td class="page_drop_down" align="center">Fol: """+self.get_page_drop_down(ms_key, current_page, html_filename)+"""</td>
		     <td align="center"><a class="pg_nav" title="No next page"><img src="pics/OE_page_Nav_next_inactive.png"/></a></td>
		     <td align="center"><a class="pg_nav" title="The current page"><img src="pics/OE_page_Nav_last_inactive.png"/></a></td>
             """)
    elif current_page == first_page and current_page == last_page:
      controls = controls % ("""
		     <td align="center"><a class="pg_nav" title="The current page"><img src="pics/OE_page_Nav_first_inactive.png"/></a></td>
		     <td align="center"><a class="pg_nav" title="No previous page"><img src="pics/OE_page_Nav_prev_inactive.png"/></a></td>
		     <td class="page_drop_down" align="center">Fol: """+self.get_page_drop_down(ms_key, current_page, html_filename)+"""</td>
		     <td align="center"><a class="pg_nav" title="No next page"><img src="pics/OE_page_Nav_next_inactive.png"/></a></td>
		     <td align="center"><a class="pg_nav" title="The current page"><img src="pics/OE_page_Nav_last_inactive.png"/></a></td>
             """)
    else:
      controls = controls % ("""
		     <td align="center"><a class="pg_nav" title="First page of this manuscript" href=\""""+name[0]+"_"+first_page+"."+name[1]+"""\"><img border="0" src="pics/OE_page_Nav_first.png"/></a></td>
		     <td align="center"><a class="pg_nav" title="Previous page of this manuscript" href=\""""+name[0]+"_"+previous_page+"."+name[1]+"""\"><img border="0" src="pics/OE_page_Nav_prev.png"/></a></td>
		     <td class="page_drop_down" align="center">Fol: """+self.get_page_drop_down(ms_key, current_page, html_filename)+"""</td>
		     <td align="center"><a class="pg_nav" title="Next page of this manuscript" href=\""""+name[0]+"_"+next_page+"."+name[1]+"""\"><img border="0" src="pics/OE_page_Nav_next.png"/></a></td>
		     <td align="center"><a class="pg_nav" title="Last page of this manuscript" href=\""""+name[0]+"_"+last_page+"."+name[1]+"""\"><img border="0" src="pics/OE_page_Nav_last.png"/></a></td>
             """)
    return controls 

  def get_page_controls_bottom(self, ms_key, current_page, html_filename):    
    print 'get_page_controls_bottom (DEBUG) MS_KEY: '+str(ms_key)
    print 'get_page_controls_bottom (DEBUG) CURRENT_PAGE: '+str(current_page)
    name = html_filename.split('.')  
    first_page = self.get_first_page(ms_key)
    previous_page = self.get_previous_page(ms_key, current_page)
    next_page = self.get_next_page(ms_key, current_page)
    last_page = self.get_last_page(ms_key)
    drop_down = ""
    controls = configMap['MSPAGECONTROLS_BOTTOM']
    if current_page == first_page and not current_page == last_page:
      controls = controls % ("""
		     <td align="center"><a class="pg_nav" title="The current page"><img src="pics/OE_page_Nav_first_inactive.png"/></a></td>
		     <td align="center"><a class="pg_nav" title="No previous page"><img src="pics/OE_page_Nav_prev_inactive.png"/></a></td>
		     <td class="page_drop_down" align="center">Fol: """+self.get_page_drop_down(ms_key, current_page, html_filename)+"""</td>
		     <td align="center"><a class="pg_nav" title="Next page of this manuscript" href=\""""+name[0]+"_"+next_page+"."+name[1]+"""\"><img border="0" src="pics/OE_page_Nav_next.png"/></a></td>
		     <td align="center"><a class="pg_nav" title="Last page of this manuscript" href=\""""+name[0]+"_"+last_page+"."+name[1]+"""\"><img border="0" src="pics/OE_page_Nav_last.png"/></a></td> 
              """)
    elif current_page == last_page and not current_page == first_page:
      controls = controls % ("""
		     <td align="center"><a class="pg_nav" title="First page of this manuscript" href=\""""+name[0]+"_"+first_page+"."+name[1]+"""\"><img border="0" src="pics/OE_page_Nav_first.png"/></a></td>
		     <td align="center"><a class="pg_nav" title="Previous page of this manuscript" href=\""""+name[0]+"_"+previous_page+"."+name[1]+"""\"><img border="0" src="pics/OE_page_Nav_prev.png"/></a></td>
		     <td class="page_drop_down" align="center">Fol: """+self.get_page_drop_down(ms_key, current_page, html_filename)+"""</td>
		     <td align="center"><a class="pg_nav" title="No next page"><img src="pics/OE_page_Nav_next_inactive.png"/></a></td>
		     <td align="center"><a class="pg_nav" title="The current page"><img src="pics/OE_page_Nav_last_inactive.png"/></a></td>
             """)
    elif current_page == first_page and current_page == last_page:
      controls = controls % ("""
		     <td align="center"><a class="pg_nav" title="The current page"><img src="pics/OE_page_Nav_first_inactive.png"/></a></td>
		     <td align="center"><a class="pg_nav" title="No previous page"><img src="pics/OE_page_Nav_prev_inactive.png"/></a></td>
		     <td class="page_drop_down" align="center">Fol: """+self.get_page_drop_down(ms_key, current_page, html_filename)+"""</td>
		     <td align="center"><a class="pg_nav" title="No next page"><img src="pics/OE_page_Nav_next_inactive.png"/></a></td>
		     <td align="center"><a class="pg_nav" title="The current page"><img src="pics/OE_page_Nav_last_inactive.png"/></a></td>
             """)
    else:
      controls = controls % ("""
		     <td align="center"><a class="pg_nav" title="First page of this manuscript" href=\""""+name[0]+"_"+first_page+"."+name[1]+"""\"><img border="0" src="pics/OE_page_Nav_first.png"/></a></td>
		     <td align="center"><a class="pg_nav" title="Previous page of this manuscript" href=\""""+name[0]+"_"+previous_page+"."+name[1]+"""\"><img border="0" src="pics/OE_page_Nav_prev.png"/></a></td>
		     <td class="page_drop_down" align="center">Fol: """+self.get_page_drop_down(ms_key, current_page, html_filename)+"""</td>
		     <td align="center"><a class="pg_nav" title="Next page of this manuscript" href=\""""+name[0]+"_"+next_page+"."+name[1]+"""\"><img border="0" src="pics/OE_page_Nav_next.png"/></a></td>
		     <td align="center"><a class="pg_nav" title="Last page of this manuscript" href=\""""+name[0]+"_"+last_page+"."+name[1]+"""\"><img border="0" src="pics/OE_page_Nav_last.png"/></a></td>
             """)
    return controls
    
  def get_page_drop_down(self, ms_key, current_page, html_filename):
    control_text = """<select style="font-size: 14px; font-weight: bold; cursor: pointer;" title="Choose a page">"""
    pages = self.database[ms_key].keys()
    if ms_key != 'Y' and ms_key != 'X' and ms_key != 'X2':
      pages.sort()
    else:
      page_numbers = []
      temp_pages = pages
      for x in temp_pages:
         if len(x) == 2:
	   if not (int(x[0]) in page_numbers):
             page_numbers.append(int(x[0]))
	 elif len(x) == 3:
	   if not (int(x[0:2]) in page_numbers):
	     page_numbers.append(int(x[0:2]))
	 elif len(x) == 4:
	   if not (int(x[0:3]) in page_numbers):
	     page_numbers.append(int(x[0:3]))
	     
      page_numbers.sort()
      #print page_numbers
      pages = []
      for x in page_numbers:
        if str(x)+'a' in temp_pages:
          pages.append(str(x)+'a')
	if str(x)+'b' in temp_pages:
	  pages.append(str(x)+'b')
	  
    name = html_filename.split('.')
    for page in pages:
      if page == current_page:
        control_text += '  <option SELECTED>'+page+"</option>"
      else:
        control_text += '  <option onclick="javascript:document.location.href=\''+name[0]+"_"+page+"."+name[1]+'\'">'+page+"</option>"
    control_text += "</select>"
    return control_text

    
  #for debug
  #
  # problem with Y pg 28b
  #
  def print_ms_page_map(self, ms_key):
    print "````````````````````````````````````````````"
    print "| -- MS --|-- PRV --|-- CURRENT PAGE --|-- NXT --|"
    pages = self.database[ms_key].keys()
    pages.sort()
    for page in pages:
      if str(self.database[ms_key][page][0]) == "":
        print "| -- "+ms_key+" --|-- N/A --|--      "+page+"      --|-- "+str(self.database[ms_key][page][1])+" --|"
        #print "| -- "+ms_key+" --|--      "+page+"      --|-- N/A --|-- "+str( self.database[ms_key][page][1] )+" --|"
      elif str(self.database[ms_key][page][1]) == "":
        print "| -- "+ms_key+" --|-- "+str(self.database[ms_key][page][0])+" --|--      "+page+"      --|-- N/A --|"
        #print "| -- "+ms_key+" --|--      "+page+"      --|-- "+str( self.database[ms_key][page][0] )+" --|-- N/A --|"
      else:
        print "| -- "+ms_key+" --|-- "+str(self.database[ms_key][page][0])+" --|--      "+page+"      --|-- "+str(self.database[ms_key][page][1])+" --|"
        #print "| -- "+ms_key+" --|--      "+page+"      --|-- "+str( self.database[ms_key][page][0] )+" --|-- "+str( self.database[ms_key][page][1] )+" --|"
    


    
# variable lpdb is a line per page database.  it lists each line number for each page for each manuscript
#
# the data structure of this is:  { ms_key: {linenumber: page#} }
#
# class must be declared here... :(
class line_page_db:
  def __init__(self, translation=False):

      self.translation = translation
      if self.translation:
        print "TRANS DEBUG"
        self.database = { 'D':{}, 'C':{}, 'S':{}, 'S2':{}, 'S3':{}, 'S4':{}, 'B':{}, 'B2':{}, 'Y':{}, 'X':{}, 'X2':{}, 'X3':{}, 'N':{}, 'Y2':{}, 'Y3':{}, 'Y4':{}}
	#print self.database
      else:  
	self.database = {'D':{}, 'C':{}, 'S':{}, 'Y':{}, 'B':{}, 'X':{}, 'N':{}}
  
  def get_key_of_trans_map(self, search_line):
    import re
    line_test = re.compile("\\d{2}[.]\\d{2}[.]\\d{2}")
    for key in self.database: #search MS key found in mask first
      if search_line[0] in key:
        #print "SEARCHING KEY("+str(search_line)+"): "+str( key )
        for line in self.database[key]:
	  #print "Checking line: "+str( line )+" == "+str( search_line )
	  if line == search_line:
	    #print "FOUND KEY for canon ("+str( search_line )+")! "+str( key )
	    return key

    for key in self.database: #search non-related MS keys
      if search_line[0] not in key:
        #print "CHECKING WITH MSKEY OF: "+str( key )
        #print "SEARCHING FOR LINE: "+str( search_line )
        #print "test: "+str( self.database )
        for line in self.database[key]:
          if line == search_line:
	    return key

    searchlinebr = search_line.split(".")
    if len(searchlinebr[0]) == 3:
      search_line = search_line[1:len(search_line)]
    elif len(seachlinebr[0]) == 4:
      search_line = search_line[2:len(search_line)]
    print "NEW SEARCH LINE: "+str(search_line)
    for key in self.database:
      #if line_no == 'B44.29.03':
      #  print "HEY!!!!", self.database['B']['B44.29.03']
      #if key == 'B':
      #  print "CHECKING WITH MSKEY OF: "+str( key )
      #  print "test: "+str( self.database[key] )
      for line in self.database[key]:
        if len(key) == 1:
          if line_test.match(line[1:len(line)]) and line[1:len(line)] == search_line:
	    return key
	elif len(key) == 2:
	  if line_test.match(line[2:len(line)]) and line[2:len(line)] == search_line:
	    return key
    return "Not Found!"
    
  def build_lpdb(self, ms_database):
    global CURRENT_MS_KEY, CURRENT_PAGE, PREVIOUS_PAGE
    for key in self.database:
      CURRENT_PAGE = ""
      CURRENT_MS_KEY = key
      MS =None
      if self.translation:
        #print "TRANS DEBUG 2"
	#print self.database
        MS = ms_database.translations[ CURRENT_MS_KEY ]['translation'].manuscript
      else:
        MS = ms_database.manuscripts[ CURRENT_MS_KEY ]['document'].manuscript
      #header = MS.getChildren("teiHeader")      
      texts = MS.getChildren("text")
      temp =[]
      body = texts[0].getChildren('body')
      line_db = None
      if self.translation:
        line_db = body[0].get_lines_per_page(translation=True)
      else:
        line_db = body[0].get_lines_per_page()
      PREVIOUS_PAGE = ""

  def add_line(self, line_no):
    global CURRENT_MS_KEY, CURRENT_PAGE
    #print self.database
    #print "ADDING LINE: " +line_no 
    #print "Key is: "+CURRENT_MS_KEY
    if self.translation:
      self.database[ CURRENT_MS_KEY ].update({line_no:CURRENT_PAGE})
    else:
      self.database[ CURRENT_MS_KEY ].update({line_no:CURRENT_PAGE})

  def print_lpdb(self):    
    for key in self.database:
      self.print_ms_lpdb(key)
      #print "-- MS Key --|--  line no  -- | -- page no --"
      #print "````````````````````````````````````````````"
      #for item in self.database[key]:
      #  print "--    "+ key +"   --|-- "+ str( item[0] ) +" -- | --   "+ str( item[1] )+ "   -- "

  def get_page(self, line):
    key = line[0]
    #if key == 'B'
    #print self.database
    if self.database.has_key(key):
      return self.database[ key ][ line ]
    else:
      return None
  def get_tpage(self, key, line):
    print "tpage DEBUG: "+str(line)
    import re
    line_test = re.compile("\\d{2}[.]\\d{2}[.]\\d{2}")
    linebd = line.split(".")
    #wipe_key_len = 0
    wipe_line_len = 0
    if len(linebd[0]) == 3:
      wipe_line_len = 1
    elif len (linebd[0]) == 4:
      wipe_line_len = 2
    #if len( key ) == 1:
    #  wipe_key_len = 0
    #elif len( key ) == 2:
    #  wipe_key_len = 1
    if self.database.has_key(key):
      return self.database[ key ][ key[0]+str(line[wipe_line_len:len(line)]) ]
    else:
      return None

  #debug info
  def print_ms_lpdb(self, ms_key):
    print "-- MS Key --|--  line no  -- | -- page no --"
    print "````````````````````````````````````````````"
    for item in self.database[ms_key]:
      print "--    "+ ms_key +"   --|-- "+ str(item) +" -- | --   "+ str(self.database[ ms_key ][ item ])+ "   -- " 
      #print "PRINT_MS_MS_LPDB DEBUG: "+str(item)	    


      
############################################
#
#  Line-page database  setup
#  MS_PG_MAPS is the page mapping
#
############################################
MS_LPDB = line_page_db()
TRANS_LPDB = line_page_db(True)
MS_PG_MAP = page_map()
TRANS_PG_MAP = page_map(True)




class TEI2(XElement):#This is the root element of the document
 def get_text(self):
   return self.getChildren('text')

class teiHeader(XElement):
  def get(self):
    print "Not yet"
    
class fileDesc(XElement):
  def get(self):
    print "not yet"

class titleStmt(XElement):
  def get(self):
    print "not yet"

class title(XElement):
  def TitletoHTML(self):
    pad = '<![CDATA[&nbsp;]]>'
    x = self
    if x.getText()[0] == '.' or x.getText()[0] == ',' or x.getText()[0] == ':' or x.getText()[0] == ';' or x.getText()[0] =='(' or x.getText()[0] =='\'' or x.getText()[0] =='"' or x.getText()[0] =='!' or x.getText()[0] =="?":
      pad = ''
    build_title ='<span style="font-weight: bold;">'+pad+x.getText()+'</span>'
    return build_title
					   

class editor(XElement):
  def get(self):
    print "not yet"

class respStmt(XElement):
  def get(self):
    print "not yet"

class resp(XElement):
  def get(self):
    print "not yet"

class name(XElement):
  def get(self):
    print "not yet"
    
class hi(XElement):
  def HitoHTML1(self):
    children = self.getChildren()
    #build_hi ='<span style="position: relative;"><span style="position: static;"><span style="position: static;">'
    build_hi = '<span style="position: relative; "><span style="position: static;">'
    build_hi += self.HitoHTML2()
    return build_hi + "</span></span>" #</span></span>"

  def HitoHTML2(self, version_compare=False):
    attrs = self.getAttributes()
    rend = attrs.getFirst('rend')
    build_hi =''
    addspan = False
    proc_children = True
    if rend == 'od':
      build_hi += '<span class="od">'
      #build_hi += self.procChildren()
      #build_hi += '</span>'
    elif rend == 'red':
      build_hi += '<span class="red">'
      #build_hi += self.procChildren()
      #build_hi += '</span>'
    elif rend == 'orange':
      build_hi += '<span class="orange">'
      #build_hi += self.procChildren()
      #build_hi += '</span>'      
    elif rend == 'orncap3':      
      build_hi += '<span class="orncap3">'
      #build_hi += self.procChildren()
      #build_hi += '</span>'
    elif rend == 'orncap2':
      build_hi += '<span class="orncap2">'
      #build_hi += self.procChildren()
      #build_hi += '</span>'
    elif rend == 'redfilled':
      proc_children= False
      if len(self.getChildren()) > 0:
        if version_compare or (len(self.getChildren('hi')) > 0):
	  build_hi += '<span style="position: relative; font-size: 20px; font-weight: strong;"><span style="position: absolute; left:-1px;" class="redfilled">'
          #build_hi += '<span style="position: relative; font-size: 20px; font-weight: strong;"><span style="position: absolute; left: -.05em;" class="redfilled">'
	  for t_child in self.getChildren('hi'):
	    build_hi += t_child.getText()
	 
	  #build_hi += self.procChildren()
	  build_hi += '</span><span style="position: relative;" class="redfilledinner">'
	  for t_child in self.getChildren('hi'):
	    build_hi += t_child.getText()
		       
	  #build_hi += self.procChildren()
	  build_hi += '</span></span>'
	else:
	  """
	  #this works for most
          build_hi += '<span style="position: relative; vertical-align: top;"><span class="redfilled">'
          build_hi += self.procChildren()
          build_hi += '</span></span><span class="redfilledinner">'
          build_hi += self.procChildren()
          build_hi += '</span>'
	  """
	  
	  #build_hi += '<div style="display: inline; position: relative; padding: 0; vertical-align: baseline;"><span style="position: absolute; left:0; top: 0; color:red; z-index:1;">'
          build_hi += '<div style="display: inline; position: relative; padding: 0; vertical-align: baseline;"><span style="position: absolute; left:0px; top: 0; color:red; z-index:1;">'
          build_hi += self.procChildren()
          build_hi += '</span><span class="redfilledinner" style="z-index: 0;">'
          build_hi += self.procChildren()
          build_hi += '</span></div>'
      else:
        #if version_compare:
	#  build_hi += '<span style="position: relative;"><span style="position: absolute; left:0px;" id="redfilled">'
        #  build_hi += self.procChildren()
	#  build_hi += '</span><span style="position: relative;" class="redfilledinner">'
        #  build_hi += self.procChildren()	  
        #  build_hi += '</span></span>'
	#else:
          build_hi += '<span style="position: relative;"><span style="position: absolute; left: -.08em;" class="redfilled">'
	  #build_hi += self.procChildren()
          build_hi += self.getText()
	  build_hi += '</span><span style="position: relative;" class="redfilledinner">'
	  #build_hi += self.procChildren()
          build_hi += self.getText()
	  build_hi += '</span></span>'
         

	  
    elif rend == 'green':
      build_hi += '<span class="green">'
      #build_hi += self.procChildren()
      #build_hi += '</span>'
    elif rend == 'black':
      build_hi += '<span class="black">'
      #build_hi += self.procChildren()
      #build_hi += '</span>'
    elif rend == 'orncap8':
      build_hi += '<span class="orncap8">'
      #build_hi += self.procChildren()
      #build_hi += '</span>'
    elif rend == 'ð2':
      build_hi += '<span class="ð2">'
      #build_hi += self.procChildren()
      #build_hi += '</span>'
    elif rend == 'orncap1.5':
      build_hi += '<span class="orncap1_5">' 
      #build_hi += self.procChildren()
      #build_hi += '</span>'
    elif rend == 'orncap4':
      build_hi += '<span class="orncap4">'
      #build_hi += self.procChildren()
      #build_hi += '</span>'
    elif rend == 'greenfilled':
      proc_children = False
      build_hi += '<span class="greenfilled">'
      build_hi += self.procChildren()
      build_hi += '</span><span class="greenfilledinner">'
      build_hi += self.procChildren()
      build_hi += '</span>'
    elif rend == 'grayfilledinline':
      proc_children = False
      build_hi += '<div style="display: inline; position: relative;"><span class="grayfilledinline">'
      build_hi += self.procChildren()
      build_hi += '</span> <span class="grayfilledinner">'
      build_hi += self.procChildren()
      build_hi += '</span></div>'
    elif rend == 'grayfilledod':
      proc_children = False
      build_hi += '<span class="grayfilledod">'
      build_hi += self.procChildren()
      build_hi += '</span><span class="grayfilledinner">'
      build_hi += self.procChildren()
      build_hi += '</span>'
    elif rend == 'grayfilled':
      proc_children = False
      build_hi += '<span class="grayfilled">'
      build_hi += self.procChildren()
      build_hi += '</span><span class="grayfilledinner">'
      build_hi += self.procChildren()
      build_hi += '</span>'
    elif rend == 'd2':
      build_hi += '<span class="d2">'
      #build_hi += self.procChildren()
      #build_hi += '</span>'
    elif rend == 'e2':
      build_hi += '<span class="e2">'
      #build_hi += self.procChildren()
      #build_hi += '</span>'
    elif rend == 'a2':
      proc_children = False
      build_hi += '<div class="a2_container">&nbsp;&nbsp;<span class="a2">'
      build_hi += self.procChildren()
      build_hi += '</span></div>'
      #build_hi += '</span>'
    elif rend == 'h2':
      proc_children = False
      pass
    elif rend == 'aelig2':
      build_hi += '<span class="aelig2">'
      #build_hi += self.procChildren()
      #build_hi += '</span>'
    elif rend == 'blue':
      build_hi += '<span class="blue">'
      #build_hi += self.procChildren()
      #build_hi += '</span>'
    elif rend == 'underlined':
      build_hi += '<span class="underlined">'
      #build_hi += self.procChildren()
      #build_hi += '</span>'
    elif rend == 'strikethrough':
      build_hi += '<span style="text-decoration: line-through;">'
    elif rend == 'ash2':
      build_hi += '<span class="ash2">'
      #build_hi += ' *CODE FOR REND=ASH2* '
    elif rend == 'N3':
      build_hi += '<span class="N3">'
      #build_hi += ' *code for REND=N3* ' 
    elif rend == 'orncap5':
      build_hi += '<span class="orncap5">'
      #build_hi += ' *CODE FOR REND=ORNCAP5* '
    elif rend == 'blackfilledinline':
      proc_children = False
      build_hi += '<span class="blackfilledinline">'
      build_hi += self.procChildren()
      build_hi += '</span><span class="blackfilledinner">'
      build_hi += self.procChildren()
      build_hi += '</span>'
    elif rend == 'blackfilledbig':
      proc_children = False
      build_hi += '<div style="display: inline; position: relative;"><span class="blackfilled">'
      build_hi += self.procChildren()
      build_hi += '</span><span class="blackfilledinner">'
      build_hi += self.procChildren()
      build_hi += '</span></div>'
    elif rend == 'blackfilled':
      proc_children = False
      build_hi += '<span class="blackfilled">'
      build_hi += self.procChildren()
      build_hi += '</span><span class="blackfilledinner">'
      build_hi += self.procChildren()
      build_hi += '</span>'
    elif rend == 'orangefilled':
      #proc_children = False
      #print "** NO CODE ** for HI TAG FOUND WITH attribute rend="+str(rend)
      #pass
      proc_children = False
      build_hi += '<span class="orangefilled">'
      build_hi += self.procChildren()
      build_hi += '</span><span class="orangefilledinner">'
      build_hi += self.procChildren()
      build_hi += '</span>'      
    elif rend == 'eth2':
      proc_children = False
      #print "** NO CODE ** for HI TAG FOUND WITH attribute rend="+str( rend )
      #pass
      #"""
      build_hi += '<span id="eth2">'
      #build_hi += ' *CODE FOR REND=eth2* '
      build_hi += '&#240;'
      build_hi += '</span>'
      #"""
    elif rend == 's2':
      proc_children = False
      build_hi += '<span id="s2">'
      build_hi += 's'
      build_hi += '</span>'
      #"""
    elif rend == 'N2':
      proc_children = False
      print "** NO CODE ** for HI TAG FOUND WITH attribute rend="+str(rend)
      pass
      """
      build_hi += '<span id="N2">'
      build_hi += ' *CODE FOR REND=N2* '
      build_hi += '</span>'
      """
    elif rend == 'black':
      build_hi += '<span class="black">'
      proc_children = False
    elif rend == 'brown':
      build_hi += '<span class="brown">'
      build_hi += self.procChildren()
      build_hi += '</span>'
      proc_children = False
      """
      build_hi += '<span id="brown">'
      build_hi += ' *CODE FOR REND=brown* '
      build_hi += '</span>'
      """
    elif rend == 'halfboxedLeftBottom':
      proc_children = False
      print "** NO CODE ** for HI TAG FOUND WITH attribute rend="+str(rend)
      pass
      """
      build_hi += '<span id="halfboxedLeftBottom">'
      build_hi += ' *CODE FOR REND=halfboxedLeftBottom* '
      build_hi += '</span>'
      """
    elif rend == 'Æ2':
      proc_children = False
      print "** NO CODE ** for HI TAG FOUND WITH attribute rend="+str(rend)
      pass
      """
      build_hi += '<span id="Æ2">'
      build_hi += ' *CODE FOR REND=Æ2* '
      build_hi +='</span>'
      """
    elif rend == "boxed in black":
      proc_children = False
      print "** NO CODE ** for HI TAG FOUND WITH attribute rend="+str(rend)
      pass
      """
      build_hi += '<span id="boxed_in_black">'
      build_hi += ' *CODE FOR REND=Boxed in black HERE* '
      build_hi += '</span>'
      """
    elif rend == "n2":    
      proc_children = False
      print "** NO CODE ** for HI TAG FOUND WITH attribute rend="+str(rend)
      pass
      """
      build_hi += '<span id="n2">'
      build_hi += ' *CODE FOR REND=n2* '
      build_hi += '</span>'
      """
    elif rend == "ð":
      proc_children = False
      pass
      """
      build_hi += '<span id="ð">'
      build_hi += ' *CODE FOR REND=ð* '
      build_hi += '</span>'
      """
    elif rend == 'AElig2':
      proc_children = False
      print "** NO CODE ** for HI TAG FOUND WITH attribute rend="+str(rend)
      pass
      """
      build_hi += '<span id="AElig2">'
      build_hi += ' *CODE FOR REND=AElig2* '
      build_hi += '</span>'
      """
    elif rend == 'ul':
      proc_children = False
      print "** NO CODE ** for HI TAG FOUND WITH attribute rend="+str(rend)
      pass
      """
      build_hi += '<span id="ul">'
      build_hi += ' *CODE FOR REND=ul* '
      build_hi += '</span>'
      """
    elif rend == 'orncap1':
      proc_children = False
      print "** NO CODE ** for HI TAG FOUND WITH attribute rend="+str(rend)
      pass
      """
      build_hi += '<span id="orncap1">'
      build_hi += ' *CODE FOR REND=orncap1* '
      build_hi += '</span>'
      """
    elif rend == 'bold':
      proc_children = False
      print "** NO CODE ** for HI TAG FOUND WITH attribute rend="+str(rend)
      pass
      """
      build_hi += '<span id="bold">'
      build_hi += ' *CODE FOR REND=bold* '
      build_hi += '</span>'
      """
    else:
      #print "** NO CODE ** for HI TAG FOUND WITH attribute rend="+str( rend )
      #build_hi += '<span>'
      #build_hi += 'ERROR NO CODE FOR rend="'+rend+'"'
      #build_hi += '<span>'
      print "********************************"
      print " ERROR FOUND                   *"      
      print "   -> REND: "+rend+"           *"
      print " - THERE IS ABSOLUTELY NO CODE *"
      print "   FOR THIS ATTRIBUTE YET!!    *"
      print "********************************"
      
			     

    #if rend != "redfilled" and rend != "greenfilled" and rend != "blackfilled":
    if proc_children:
      build_hi += self.procChildren()
      build_hi += '</span>'
  
    return build_hi

  def procChildren(self):
    temp = self.getText()
    DEBUG = False #True
    if DEBUG:
      print '<br/>DEBUG<br/>'
      print 'TEMP: '+temp+'<br/>'      
      print '<br/>'

    children = self.getChildren()
    #for x in children:
     
    filler = ""
    end = ""
    real_end = "" #use if flip is set to true
    build_hi = ""
    if len(children) > 0:
      for h_child in children:
        pos = temp.find('<-*->')
        filler = ""
	real_end = ""
        flip = False
        if pos != -1:
          if h_child.__class__ == lb:
	    filler += h_child.LBtoHTML()
	    #filler += " *LB CODE HERE* "
	  elif h_child.__class__ == note:
	    filler += h_child.NotetoHTML()
	    #filler += " *NOTE CODE HERE* "
	  elif h_child.__class__ == milestone:
	    #filler += " *NEED TO CODE MILESTONE* "
	    filler += h_child.MilestonetoHTML()
	  elif h_child.__class__ == add:
	    #filler += " *NEED TO CODE ADD* "
	    filler += h_child.AddtoHTML()
	    #pass
	  elif h_child.__class__ == hi:
	    #filler += " *NEED TO CODE HI* "
	    filler += h_child.HitoHTML2()
	  elif h_child.__class__ == expan:
	    filler += h_child.ExpantoHTML()
	    #filler += " *EPAN CODE HERE* "
	  elif h_child.__class__ == dell: #might need to change this..... not sure
	    #filler += " *NEED TO CODE DELL* "
	    filler += h_child.DelltoHTML()
	  elif h_child.__class__ == corr:
	    filler += h_child.CorrtoHTML()
	  elif h_child.__class__ == damage:
	    #filler += " *NEED TO CODE DAMAGE* "
	    filler += h_child.DamagetoHTML()
	  elif h_child.__class__ == space:
	    #filler += " *NEED TO CODE SPACE* "
	    filler += h_child.SpacetoHTML()
	  elif h_child.__class__ == term:
	    #filler += " *NEED TO CODE SPACE* "
	    filler += h_child.termtoHTML()
	  else:
	    pass
	    
          #if h_child.__class__ == lb:
          #  filler += h_child.LBtoHTML()
          #elif h_child.__class__ == hi:
          #  filler += h_child.HitoHTML2()
	    
          #else:
          #  pass
          if pos > 0: #text comes before placemarker
            end = temp[0:pos]
            temp = temp[pos+5:len(temp)]
	    next_pos = temp.find('<-*->')
	    if next_pos == -1:
              real_end = temp
	    #else:
	    #   next_pos += 5
	    #   temp = temp[next_pos:len(temp)]
	       
            flip = True
	    
          elif pos == 0: #text comes after placemarker
            if pos+5 > len(temp):
              #print "<br/>TEMP -2: "+ temp +"<br/>"
              end = ""
            else:
              temp2 = temp[5:len(temp)]
              #print "<br/>DEBUG(temp2): " + temp2 +"<br/>"
              next_pos = temp2.find('<-*->')
              if next_pos != -1:
                next_pos += 5 #account for offset
                end = temp[5:next_pos]
                temp = temp[next_pos:len(temp)]
              else:
                end = temp2
                #pos = -1
                #next_pos = len(temp)

          #temp = temp[next_pos:len(temp)]
          else:
            end = ""
            temp = temp[5:len(temp)]

          if flip == False:
            build_hi += filler + end
          else:
            build_hi += end + filler + real_end

        else:
          #print "DEBUG(end temp): " + temp
          build_hi += temp
          #pass
    else:
      build_hi += temp
      temp =""
    if DEBUG:
      print "<br/>DEBUG<br/>"
      print "build_hi: " + build_hi
      print "<br/>"
    #if len(temp) != 0:
    #  build_hi += temp
    return build_hi

  def HitoHTML3(self):
    attrs = self.getAttributes()
    rend = attrs.getFirst('rend')
    children = self.getChildren()
    build_hi =''
    temp = self.getText()
    filler = ""
    end = ""
    #if temp.find("<-*->") == -1:
     # print "DEBUG(rend): "+rend 
    #  return temp
    #return " *need to code HI* "
    
    if rend == 'od':
      #build_hi += '<br><span id="od">'
      build_hi += '<span id="od">'
      if len(children) > 0:
        for child in children:
	  if child.__class__ == hi:
	    build_hi += child.HitoHTML3()
	  elif child.__class__ == lb:
	    build_hi += child.LBtoHTML()
        build_hi += '</span>'
      else:
        #print "DEBUG(hi): adding text!"	
        build_hi += self.getText()
        build_hi += '</span>'
    elif rend == 'red':
      build_hi += '<span id="red">'
      if len(children) > 0:        
        for child in children:
	  if child.__class__ == hi:
            build_hi += child.HitoHTML3()
          elif child.__class__ == lb:
            build_hi += child.LBtoHTML()         
	build_hi += '</span>'
      else:
        #print "DEBUG(hi): adding text!"	
        build_hi += self.getText()
	build_hi += '</span>'
    elif rend == 'orncap3':
      build_hi += '<span id="orncap3">'
      if len(children) > 0:
        for child in children:
	  if child.__class__ == hi:
            build_hi += child.HitoHTML3()
          elif child.__class__ == lb:
            build_hi += child.LBtoHTML()
	build_hi += '</span>' 
      else:
        #print "DEBUG(hi): adding text!"
        build_hi += self.getText()
	build_hi += '</span>'
    elif rend == 'orncap2':
      build_hi += '<span id="orncap2">'
      if len(children) > 0:
        for child in children:
          if child.__class__ == hi:
            build_hi += child.HitoHTML3()
          elif child.__class__ == lb:
            build_hi += child.LBtoHTML()
        build_hi += '</span>'
      else:
        #print "DEBUG(hi): adding text!"	
        build_hi += self.getText()
        build_hi += '</span>'
	
    elif rend == 'redfilled':
      proc_children = False #tells us if we found any children in this one if so the we process them 'early'
      #if self.getText().find('<-*->') == -1:
      if len(children) == 0:
        #build_hi += "DEBUG!!"
        #build_hi += '<span style="position: relative;"><span style="position: relative;"><span id="redfilled">'+self.getText()+'</span><span id="redfilledinner">'
	#build_hi += '<span style="position: static;"><span style="position: relative;">'
	build_hi += '<span id="redfilled">'+self.getText()+'</span><span id="redfilledinner">'
      else:
        build_hi += '<span id="redfilled">'
	if len(children) > 0:
	  proc_children = True
	  for child in children:
	    if child.__class__ == hi:
	      build_hi += child.HitoHTML3()
	    elif child.__class__ == lb:
	      build_hi += child.LBtoHTML()
	  build_hi += '</span><span id="redfilledinner">'
	  for child in children:
	    if child.__class__ == hi:
	      build_hi += child.HitoHTML3()
	    elif child.__class__ == lb:
	      build_hi += child.LBtoHTML()
	  build_hi += '</span>'
	else:
	  build_hi += self.getText()
	  build_hi += '</span>'
	  
      if len(children) > 0 and proc_children == False:
        for child in children:
          if child.__class__ == hi:
            build_hi += child.HitoHTML3()
          elif child.__class__ == lb:
            build_hi += child.LBtoHTML()
	build_hi += '</span></span></span>'
      else:
        #print "DEBUG(hi): adding text!"
        if proc_children == False:
	  build_hi += self.getText()
	  build_hi += '</span></span></span>'
	  
    elif rend == 'green':
      build_hi += '<span id="green">'
      if len(children) > 0:
        for child in children:
          if child.__class__ == hi:
            build_hi += child.HitoHTML3()
          elif child.__class__ == lb:
	    build_hi += child.LBtoHTML()
        build_hi += '</span>'
      else:
        #print "DEBUG(hi): adding text!"
	build_hi += self.getText()
	build_hi += '</span>'
    elif rend == 'black':
      build_hi += '<span id="black">'
      if len(children) > 0:
        for child in children:
          if child.__class__ == hi:
            build_hi += child.HitoHTML3()
          elif child.__class__ == lb:
            build_hi += child.LBtoHTML()
        build_hi += '</span>'    
      else:
        #print "DEBUG(hi): adding text!"
        build_hi += self.getText()
        build_hi += '</span>'
    elif rend == 'orncap8':
      build_hi += '<span id="orncap8">'
      if len(children) > 0:
        for child in children:
          if child.__class__ == hi:
            build_hi += child.HitoHTML3()
          elif child.__class__ == lb:
            build_hi += child.LBtoHTML()
        build_hi += '</span>'
      else:
        #print "DEBUG(hi): adding text!"
        build_hi += self.getText()
        build_hi += '</span>'
    elif rend == 'ð2':
      build_hi += '<span id="ð2">'
      if len(children) > 0:
        for child in children:
          if child.__class__ == hi:
            build_hi += child.HitoHTML3()
          elif child.__class__ == lb:
            build_hi += child.LBtoHTML()
        build_hi += '</span>'
      else:
        #print "DEBUG(hi): adding text!"
        build_hi += self.getText()
        build_hi += '</span>'
    elif rend == 'orncap1.5':
      build_hi += '<span id="orncap1_5">'
      if len(children) > 0:
        for child in children:
          if child.__class__ == hi:
            build_hi += child.HitoHTML3()
          elif child.__class__ == lb:
            build_hi += child.LBtoHTML()
        build_hi += '</span>'
      else:
        #print "DEBUG(hi): adding text!"
        build_hi += self.getText()
        build_hi += '</span>'
    elif rend == 'orncap4':
      build_hi += '<span id="orncap4">'
      if len(children) > 0:
        for child in children:
          if child.__class__ == hi:
            build_hi += child.HitoHTML3()
          elif child.__class__ == lb:
            build_hi += child.LBtoHTML()
        build_hi += '</span>'
      else:
        #print "DEBUG(hi): adding text!"
        build_hi += self.getText()
        build_hi += '</span>'
    elif rend == 'greenfilled':
      build_hi += '<span id="greenfilled">'+self.getText()+'</span><span id="greenfilledinner">'
      if len(children) > 0:
        for child in children:
          if child.__class__ == hi:
            build_hi += child.HitoHTML3()
          elif child.__class__ == lb:
            build_hi += child.LBtoHTML()
        build_hi += '</span>'
      else:
        #print "DEBUG(hi): adding text!"

        build_hi += self.getText()
        build_hi += '</span>'

    elif rend == 'd2':
      build_hi += '<span id="d2">'
      if len(children) > 0:
        for child in children:
          if child.__class__ == hi:
            build_hi += child.HitoHTML3()
          elif child.__class__ == lb:
            build_hi += child.LBtoHTML()
        build_hi += '</span>'
      else:
        #print "DEBUG(hi): adding text!"
        build_hi += self.getText()
        build_hi += '</span>'
    elif rend == 'e2':
      build_hi += '<span id="e2">'
      if len(children) > 0:
        for child in children:
          if child.__class__ == hi:
            build_hi += child.HitoHTML3()
          elif child.__class__ == lb:
            build_hi += child.LBtoHTML()
        build_hi += '</span>'
      else:
        #print "DEBUG(hi): adding text!"
        build_hi += self.getText()
        build_hi += '</span>'
    elif rend == 'a2':
      build_hi += '<span id="a2">'
      if len(children) > 0:
        for child in children:
          if child.__class__ == hi:
            build_hi += child.HitoHTML3()
          elif child.__class__ == lb:
            build_hi += child.LBtoHTML()
        build_hi += '</span>'
      else:
        #print "DEBUG(hi): adding text!"
        build_hi += self.getText()
        build_hi += '</span>'
    elif rend == 'aelig2':
      build_hi += '<span id="aelig2">'
      if len(children) > 0:
        for child in children:
          if child.__class__ == hi:
            build_hi += child.HitoHTML3()
          elif child.__class__ == lb:
            build_hi += child.LBtoHTML()
        build_hi += '</span>'
      else:
        #print "DEBUG(hi): adding text!"
        build_hi += self.getText()
        build_hi += '</span>'
    else:
      print "*************"
      print "*ERROR FOUND*"
      print "*************"
      print "-> REND: "+rend
      print ""

    return build_hi #+ '</span>'
				      

class publicationStmt(XElement):
  def get(self):
    print "not yet"

class publisher(XElement):
  def get(self):
    print "not yet"

class pubPlace(XElement):
  def get(self):
    print "not yet"

class idno(XElement):
  def get(self):
    print "not yet"

class availability(XElement):
  def get(self):
    print "not yet"

class p(XElement):
  def get_p_version(self):
    temp = self.getText()
    DEBUG = False #True
    if DEBUG:
      print '<br/>DEBUG<br/>'
      print 'TEMP: '+temp+'<br/>'
      print '<br/>'
      
    children = self.getChildren()
    filler = ""
    end = ""
    real_end = "" #use if flip is set to true
    build_hi = ""
    if len(children) > 0:
      for h_child in children:
        pos = temp.find('<-*->')
        filler = ""
        real_end = ""
        flip = False
        if pos != -1:
          if h_child.__class__ == lb:
            filler += h_child.LBtoHTML()
            #filler += " *LB CODE HERE* "
          elif h_child.__class__ == note:
            filler += h_child.NotetoHTML()
            #filler += " *NOTE CODE HERE* "
            #pass
          elif h_child.__class__ == milestone:
	    #
	    # Due to a data change in version 2 there should be no milestone 
	    # page markers inside of any p elements
	    #
	    #
            #filler += " *NEED TO CODE MILESTONE* "
            #filler += h_child.MilestonetoHTML()
	    #attrs = h_child.getAttributes()
            #unit = attrs.getFirst('unit')
	    
            filler += "<br/><br/>"
          elif h_child.__class__ == add:
            #filler += " *NEED TO CODE ADD* "
            filler += h_child.AddtoHTML_no_margin()
            
          elif h_child.__class__ == hi:
            #filler += " *NEED TO CODE HI* "
            filler += h_child.HitoHTML2(True)
          elif h_child.__class__ == expan:
            filler += h_child.ExpantoHTML()
            #filler += " *EPAN CODE HERE* "
          elif h_child.__class__ == dell: #might need to change this..... not sure
            #filler += " *NEED TO CODE DELL* "
            filler += h_child.DelltoHTML()
          elif h_child.__class__ == corr:
            filler += h_child.CorrtoHTML()
            #filler += " *NEED TO CODE COR* "
          elif h_child.__class__ == damage:
	    #filler += " *NEED TO CODE DAMAGE* "
            #filler += h_child.DamagetoHTML_no_popup()
	    filler += h_child.DamagetoHTML()
          elif h_child.__class__ == space:
            #filler += " *NEED TO CODE SPACE* "
            #filler += h_child.SpacetoHTML()
	    pass
          else:
            pass
          if pos > 0: #text comes before placemarker
            end = temp[0:pos]
            temp = temp[pos+5:len(temp)]
            next_pos = temp.find('<-*->')
            if next_pos == -1:
              real_end = temp
            #else:
            #   next_pos += 5
            #   temp = temp[next_pos:len(temp)]

            flip = True

          elif pos == 0: #text comes after placemarker
            if pos+5 > len(temp):
              #print "<br/>TEMP -2: "+ temp +"<br/>"
              end = ""
            else:
              temp2 = temp[5:len(temp)]
              #print "<br/>DEBUG(temp2): " + temp2 +"<br/>"
              next_pos = temp2.find('<-*->')
              if next_pos != -1:
                next_pos += 5 #account for offset
                end = temp[5:next_pos]
                temp = temp[next_pos:len(temp)]
              else:
                end = temp2
                #pos = -1
                #next_pos = len(temp)

          #temp = temp[next_pos:len(temp)]
          else:
            end = ""
            temp = temp[5:len(temp)]

          if flip == False:
            build_hi += filler + end
          else:
            build_hi += end + filler + real_end

        else:
          #print "DEBUG(end temp): " + temp
          build_hi += temp
          #pass
    else:
      build_hi += temp
      temp =""
    if DEBUG:
      print "<br/>DEBUG<br/>"
      print "build_hi: " + build_hi
      print "<br/>"
    #if len(temp) != 0:
    #  build_hi += temp
    return build_hi

				  
  def get_p_text(self):
    temp = self.getText()
    DEBUG = False #True
    if DEBUG:
      print '<br/>DEBUG<br/>'
      print 'TEMP: '+temp+'<br/>'
      print '<br/>'
    
    children = self.getChildren()
    filler = ""
    end = ""
    real_end = "" #use if flip is set to true
    build_hi = ""
    if len(children) > 0:
      for h_child in children:
        pos = temp.find('<-*->')
        filler = ""
        real_end = ""
        flip = False
        if pos != -1:
          if h_child.__class__ == lb:
            #filler += h_child.LBtoHTML()
            filler += " *LB CODE HERE* "
          elif h_child.__class__ == note:
            #filler += h_child.NotetoHTML()
            #filler += " *NOTE CODE HERE* "
	    pass
          elif h_child.__class__ == milestone:
            #filler += " *NEED TO CODE MILESTONE* "
            #filler += h_child.MilestonetoHTML()
	    pass
          elif h_child.__class__ == add:
            #filler += " *NEED TO CODE ADD* "
            #filler += h_child.AddtoHTML()
	    pass
          elif h_child.__class__ == hi:
            filler += " *NEED TO CODE HI* "
            #filler += h_child.HitoHTML2()
          elif h_child.__class__ == expan:
            #filler += h_child.ExpantoHTML()
            filler += " *EPAN CODE HERE* "
          elif h_child.__class__ == dell: #might need to change this..... not sure
            filler += " *NEED TO CODE DELL* "
            #filler += h_child.DelltoHTML()
          elif h_child.__class__ == corr:
            #filler += h_child.CorrtoHTML()
            filler += " *NEED TO CODE COR* "
          elif h_child.__class__ == damage:
            filler += " *NEED TO CODE DAMAGE* "
            #filler += h_child.DamagetoHTML()
          elif h_child.__class__ == space:
            filler += " *NEED TO CODE SPACE* "
            #filler += h_child.SpacetoHTML()
          else:
            pass
          if pos > 0: #text comes before placemarker
            end = temp[0:pos]
            temp = temp[pos+5:len(temp)]
            next_pos = temp.find('<-*->')
            if next_pos == -1:
              real_end = temp
            #else:
            #   next_pos += 5
            #   temp = temp[next_pos:len(temp)]

            flip = True

          elif pos == 0: #text comes after placemarker
            if pos+5 > len(temp):
              #print "<br/>TEMP -2: "+ temp +"<br/>"
              end = ""
            else:
              temp2 = temp[5:len(temp)]
              #print "<br/>DEBUG(temp2): " + temp2 +"<br/>"
              next_pos = temp2.find('<-*->')
              if next_pos != -1:
                next_pos += 5 #account for offset
                end = temp[5:next_pos]
                temp = temp[next_pos:len(temp)]
              else:
                end = temp2
                #pos = -1
                #next_pos = len(temp)

          #temp = temp[next_pos:len(temp)]
          else:
            end = ""
            temp = temp[5:len(temp)]

          if flip == False:
            build_hi += filler + end
          else:
            build_hi += end + filler + real_end

        else:
          #print "DEBUG(end temp): " + temp
          build_hi += temp
          #pass
    else:
      build_hi += temp
      temp =""
    if DEBUG:
      print "<br/>DEBUG<br/>"
      print "build_hi: " + build_hi
      print "<br/>"
    #if len(temp) != 0:
    #  build_hi += temp
    return build_hi



  def PtoHTML(self):
    temp = self.getText()
    DEBUG = False #True
    if DEBUG:
      print '<br/>DEBUG<br/>'
      print 'TEMP: '+temp+'<br/>'      
      print '<br/>'

    children = self.getChildren()
    filler = ""
    end = ""
    real_end = "" #use if flip is set to true
    build_hi = '<span class="p">'
    if len(children) > 0:
      for h_child in children:
        pos = temp.find('<-*->')
        filler = ""
	real_end = ""
        flip = False
        if pos != -1:
          if h_child.__class__ == lb:
	    filler += h_child.LBtoHTML()
	    #filler += " *LB CODE HERE* "
	  elif h_child.__class__ == term:
	    filler += h_child.termtoHTML()
	  elif h_child.__class__ == note:
	    filler += h_child.NotetoHTML()
	    #filler += " *NOTE CODE HERE* "
	  elif h_child.__class__ == milestone:
	    #filler += " *NEED TO CODE MILESTONE* "
	    filler += h_child.MilestonetoHTML()
	  elif h_child.__class__ == add:
	    #filler += " *CODE ADD* "
	    filler += h_child.AddtoHTML()
	  elif h_child.__class__ == hi:
	    #there seems there may be a problem with the hi rendering on large manuscripts...here is where u disable that by commenting it out and adding the "Need to code hi" instead
	    #filler += " *NEED TO CODE HI* "
	    filler += h_child.HitoHTML2()
	  elif h_child.__class__ == expan:
	    filler += h_child.ExpantoHTML()
	    #filler += " *EPAN CODE HERE* "
	  elif h_child.__class__ == dell: #might need to change this..... not sure
	    #filler += " *NEED TO CODE DELL* "
	    filler += h_child.DelltoHTML()
	  elif h_child.__class__ == corr:
	    filler += h_child.CorrtoHTML()
	  elif h_child.__class__ == damage:
	    #filler += " *NEED TO CODE DAMAGE* "
	    filler += h_child.DamagetoHTML()
	  elif h_child.__class__ == space:
	    #filler += " *NEED TO CODE SPACE* "
	    filler += h_child.SpacetoHTML()
	  else:
	    pass
	    
          #if h_child.__class__ == lb:
          #  filler += h_child.LBtoHTML()
          #elif h_child.__class__ == hi:
          #  filler += h_child.HitoHTML2()
	    
          #else:
          #  pass
          if pos > 0: #text comes before placemarker
            end = temp[0:pos]
            temp = temp[pos+5:len(temp)]
	    next_pos = temp.find('<-*->')
	    if next_pos == -1:
              real_end = temp
	    #else:
	    #   next_pos += 5
	    #   temp = temp[next_pos:len(temp)]
	       
            flip = True
	    
          elif pos == 0: #text comes after placemarker
            if pos+5 > len(temp):
              #print "<br/>TEMP -2: "+ temp +"<br/>"
              end = ""
            else:
              temp2 = temp[5:len(temp)]
              #print "<br/>DEBUG(temp2): " + temp2 +"<br/>"
              next_pos = temp2.find('<-*->')
              if next_pos != -1:
                next_pos += 5 #account for offset
                end = temp[5:next_pos]
                temp = temp[next_pos:len(temp)]
              else:
                end = temp2
                #pos = -1
                #next_pos = len(temp)

          #temp = temp[next_pos:len(temp)]
          else:
            end = ""
            temp = temp[5:len(temp)]

          if flip == False:
            build_hi += filler + end
          else:
            build_hi += end + filler + real_end

        else:
          #print "DEBUG(end temp): " + temp
          build_hi += temp
          #pass
    else:
      build_hi += temp
      temp =""
    if DEBUG:
      print "<br/>DEBUG<br/>"
      print "build_hi: " + build_hi
      print "<br/>"
    #if len(temp) != 0:
    #  build_hi += temp
    return build_hi + '</span>'


  def getTextOnly(self):
    temp = self.getText()
    DEBUG = False #True
    if DEBUG:
      print '<br/>DEBUG<br/>'
      print 'TEMP: '+temp+'<br/>'
      print '<br/>'

    children = self.getChildren()
    build_p = ""
    if len(children) > 0:
      for h_child in children:
        pos = temp.find('<-*->')
        filler = ""
        if pos != -1:
          if h_child.__class__ == lb:
            filler += h_child.LBtoHTML()
            #filler += " *LB CODE HERE* "
          elif h_child.__class__ == note:
            #filler += h_child.NotetoHTML()
	    
            pass
          elif h_child.__class__ == milestone:
            
            #filler += h_child.MilestonetoHTML()
	    pass
          elif h_child.__class__ == add:
            #filler += " *NEED TO CODE ADD* "
            #filler += h_child.AddtoHTML()
	    pass
          elif h_child.__class__ == hi:
            
            #filler += h_child.HitoHTML2()
	    filler += h_child.getText()
          elif h_child.__class__ == expan:
            filler += h_child.ExpantoHTML()
            #filler += " *EPAN CODE HERE* "
          elif h_child.__class__ == dell: #might need to change this..... not sure
            
	    #	    filler += h_child.DelltoHTML()
	    filler += h_child.getText()
          elif h_child.__class__ == corr:
            #filler += h_child.CorrtoHTML()
	    filler += h_child.getText()
          elif h_child.__class__ == damage:
            #filler += " *NEED TO CODE DAMAGE* "
            #filler += h_child.DamagetoHTML()
	    filler += h_child.getText()
          elif h_child.__class__ == space:
            #filler += " *NEED TO CODE SPACE* "
            filler += h_child.SpacetoHTML()
          else:
            pass

        build_p += filler
    return build_p

class date(XElement):
  def get(self):
    print "not yet"

class sourceDesc(XElement):
  def get(self):
    print "not yet"

class biblFull(XElement):
  def get(self):
    print "not yet"

class editionStmt(XElement):
  def get(self):
    print "not yet"

class extent(XElement):
  def get(self):
    print "not yet"

class seriesStmt(XElement):
  def get(self):
    print "not yet"

class encodingDesc(XElement):
  def get(self):
    print "not yet"

class editorialDecl(XElement):
  def get(self):
    print "not yet"

class list(XElement): #be warned list is a function of python...you must now call it specially
  def get(self):
   print "not yet"

class head(XElement):
  def get(self):
    print "not yet"

class item(XElement):
  def get(self):
    print "not yet"

class label(XElement):
  def get(self):
    print "not yet"

class term(XElement):
  def termtoHTML(self):
    temp = self.getText()
    DEBUG = False #True
    if DEBUG:
      print '<br/>DEBUG<br/>'
      print 'TEMP: '+temp+'<br/>'      
      print '<br/>'

    children = self.getChildren()
    filler = ""
    end = ""
    real_end = "" #use if flip is set to true
    build_hi = ""
    if len(children) > 0:
      for h_child in children:
        pos = temp.find('<-*->')
        filler = ""
	real_end = ""
        flip = False
        if pos != -1:
          if h_child.__class__ == lb:
	    filler += h_child.LBtoHTML()
	    #filler += " *LB CODE HERE* "
	  elif h_child.__class__ == note:
	    filler += h_child.NotetoHTML()
	    #filler += " *NOTE CODE HERE* "
	  elif h_child.__class__ == milestone:
	    #filler += " *NEED TO CODE MILESTONE* "
	    filler += h_child.MilestonetoHTML()
	  elif h_child.__class__ == add:
	    #filler += " *NEED TO CODE ADD* "
	    filler += h_child.AddtoHTML()
	  elif h_child.__class__ == hi:
	    #filler += " *NEED TO CODE HI* "
	    filler += h_child.HitoHTML2()
	  elif h_child.__class__ == expan:
	    filler += h_child.ExpantoHTML()
	    #filler += " *EPAN CODE HERE* "
	  elif h_child.__class__ == dell: #might need to change this..... not sure
	    #filler += " *NEED TO CODE DELL* "
	    filler += h_child.DelltoHTML()
	  elif h_child.__class__ == corr:
	    filler += h_child.CorrtoHTML()
	  elif h_child.__class__ == damage:
	    #filler += " *NEED TO CODE DAMAGE* "
	    filler += h_child.DamagetoHTML()
	  elif h_child.__class__ == space:
	    #filler += " *NEED TO CODE SPACE* "
	    filler += h_child.SpacetoHTML()
	  else:
	    pass
	    
          #if h_child.__class__ == lb:
          #  filler += h_child.LBtoHTML()
          #elif h_child.__class__ == hi:
          #  filler += h_child.HitoHTML2()
	    
          #else:
          #  pass
          if pos > 0: #text comes before placemarker
            end = temp[0:pos]
            temp = temp[pos+5:len(temp)]
	    next_pos = temp.find('<-*->')
	    if next_pos == -1:
              real_end = temp
	    #else:
	    #   next_pos += 5
	    #   temp = temp[next_pos:len(temp)]
	       
            flip = True
	    
          elif pos == 0: #text comes after placemarker
            if pos+5 > len(temp):
              #print "<br/>TEMP -2: "+ temp +"<br/>"
              end = ""
            else:
              temp2 = temp[5:len(temp)]
              #print "<br/>DEBUG(temp2): " + temp2 +"<br/>"
              next_pos = temp2.find('<-*->')
              if next_pos != -1:
                next_pos += 5 #account for offset
                end = temp[5:next_pos]
                temp = temp[next_pos:len(temp)]
              else:
                end = temp2
                #pos = -1
                #next_pos = len(temp)

          #temp = temp[next_pos:len(temp)]
          else:
            end = ""
            temp = temp[5:len(temp)]

          if flip == False:
            build_hi += filler + end
          else:
            build_hi += end + filler + real_end

        else:
          #print "DEBUG(end temp): " + temp
          build_hi += temp
          #pass
    else:
      build_hi += temp
      temp =""
    if DEBUG:
      print "<br/>DEBUG<br/>"
      print "build_hi: " + build_hi
      print "<br/>"
    #if len(temp) != 0:
    #  build_hi += temp
    return build_hi

  def termtoHTML_old(self):
    return self.getText()

  def get(self):
    print "not yet"

class profileDesc(XElement):
  def get(self):
    print "not yet"

class langUsage(XElement):
  def get(self):
    print "not yet"

class language(XElement):
  def get(self):
    print "not yet"

class handList(XElement):
  def get(self):
    print "not yet"

class hand(XElement):
  def get(Self):
    print "not yet"

class revisionDesc(XElement):
  def get(self):
    print "not yet"

class change(XElement):
  def get(self):
    print "not yet"

class text(XElement):
  def get(self):
    print "not yet"

class body(XElement):
  def BodytoHTML_paged(self, database=None):
    global HTML_STACK, CURRENT_FILE, TRANS_LPDB, MS_LPDB, TRANS_PG_MAP, MS_PG_MAP, CURRENT_MS_KEY
    HTML_STACK.push(['<span class="body">', '</span>'])
    CURRENT_FILE.add_text('<span class="body">')    
    for b_child in self.getChildren():
      if b_child.__class__ == lb: #Linebreaks are not added to HTML_STACK because they contain not inner elements, attributes, or text
        b_child.LBtoHTML_paged()
      elif b_child.__class__ == div1:
        b_child.Div1toHTML_paged(database)
      elif b_child.__class__ == column:
        b_child.ColumntoHTML(database)
      elif b_child.__class__ == milestone:
        if b_child.is_page_marker():
	  if CURRENT_FILE.is_name_set():
	    #print "DEBUG: FILE NAME IS SET!"
	    #end current page to start a new one
	    CURRENT_FILE.add_text(HTML_STACK.closing_contents()) #close open tags
	    #
	    # ADD PAGE NAVGATION HERE!!
	    #			    
	    #CURRENT_FILE.add_text( HTML_PAGE_CLOSE ) #close page
	    CURRENT_FILE.text_close(database)
            CURRENT_FILE.write()  #write the file	  
	    
	    #START NEW PAGE
	    CURRENT_FILE.set_filename(FILENAMES[CURRENT_MS_KEY], b_child.get_page_number())
	    #CURRENT_FILE.add_text( HTML_PAGE_OPEN )
	    CURRENT_FILE.text_open(database)
	    CURRENT_FILE.add_text(HTML_STACK.opening_contents())    
	    CURRENT_FILE.add_text(b_child.MilestonetoHTML())
	    
	  else: #first page of MS
	    #start new page
	    CURRENT_FILE.set_filename(FILENAMES[CURRENT_MS_KEY], b_child.get_page_number())
    	CURRENT_FILE.text_open(database)
    	#CURRENT_FILE.add_MS_header( database.get_MS_name( CURRENT_MS_KEY ) )
    	CURRENT_FILE.add_text(b_child.MilestonetoHTML())
	    
    CURRENT_FILE.add_text(HTML_STACK.closing_contents())
    HTML_STACK.pop()
    #CURRENT_FILE.add_text( HTML_PAGE_CLOSE )
    CURRENT_FILE.text_close(database)
    CURRENT_FILE.write()
   
  # this is for the translation pages 
  def BodytoHTML_tpaged(self, database=None):
    global HTML_STACK, CURRENT_FILE, MS_LPDB, MS_PG_MAP, CURRENT_MS_KEY
    HTML_STACK.push(['<span class="body">', '</span>'])
    CURRENT_FILE.add_text('<span class="body">')    
    for b_child in self.getChildren():
      if b_child.__class__ == lb: #Linebreaks are not added to HTML_STACK because they contain no inner elements, attributes, or text
        b_child.LBtoHTML_paged()
      elif b_child.__class__ == div1:
        b_child.Div1toHTML_tpaged(database)
      elif b_child.__class__ == milestone:
        if b_child.is_page_marker():
	  if CURRENT_FILE.is_name_set():
	    #print "DEBUG: FILE NAME IS SET!"
	    #end current page to start a new one
	    CURRENT_FILE.add_text(HTML_STACK.closing_contents()) #close open tags
	    #
	    # ADD PAGE NAVGATION HERE!!
	    #			    
	    #CURRENT_FILE.add_text( HTML_PAGE_CLOSE ) #close page
	    CURRENT_FILE.text_close(database)
            CURRENT_FILE.write()  #write the file	  
	    
	    #START NEW PAGE
	    CURRENT_FILE.set_filename(TRANS_FILENAMES[CURRENT_MS_KEY], b_child.get_page_number())
	    #CURRENT_FILE.add_text( HTML_PAGE_OPEN )
	    CURRENT_FILE.text_open(database)
	    CURRENT_FILE.add_text(HTML_STACK.opening_contents())    
	    CURRENT_FILE.add_text(b_child.MilestonetoHTML())
	    
	  else: #first page of MS
	    #start new page
	    CURRENT_FILE.set_filename(TRANS_FILENAMES[CURRENT_MS_KEY], b_child.get_page_number())
	    CURRENT_FILE.text_open(database)
	    #CURRENT_FILE.add_MS_header( database.get_MS_name( CURRENT_MS_KEY ) )
	    CURRENT_FILE.add_text(b_child.MilestonetoHTML())
	    
    CURRENT_FILE.add_text(HTML_STACK.closing_contents())
    HTML_STACK.pop()
    #CURRENT_FILE.add_text( HTML_PAGE_CLOSE )
    CURRENT_FILE.text_close(database)
    CURRENT_FILE.write()
  
  def BodytoHTML(self, database=None):
    build_body = '<span class="body">'
    for b_child in self.getChildren():
      if b_child.__class__ == lb:
        build_body += b_child.LBtoHTML()
      elif b_child.__class__ == div1:
        build_body += b_child.Div1toHTML(database)
      elif b_child.__class__ == milestone:
        build_body += b_child.MilestonetoHTML()
    return build_body + '</span>'
    
  def get_lines_per_page(self, translation=False):
    global CURRENT_PAGE, CURRENT_MS_KEY, TRANS_LPDB, MS_LPDB, TRANS_PG_MAP, MS_PG_MAP, PREVIOUS_PAGE, LAST_PAGE, FIRST_PAGE
    child_number = 1
    for b_child in self.getChildren():    
      #print str(child_number)+": "+str( b_child.name )
      #child_number +=1      
      #if b_child.__class__ == lb:
      #  build_body += b_child.LBtoHTML()
      if b_child.__class__ == div1:
        #build_body += b_child.Div1toHTML(database)
	b_child.get_lines_per_page(translation)
      elif b_child.__class__ == milestone:
        if b_child.is_page_marker():
	  #print "CURRENT PAGE BEFORE ASSIGN: "+ CURRENT_PAGE
	  if CURRENT_PAGE != "":
	    #print "NOT FIRST PAGE!"
	    if translation:
	      TRANS_PG_MAP.update_page(CURRENT_MS_KEY, CURRENT_PAGE, PREVIOUS_PAGE, b_child.get_page_number())
	    else:
	      MS_PG_MAP.update_page(CURRENT_MS_KEY, CURRENT_PAGE, PREVIOUS_PAGE, b_child.get_page_number())#set last current page in page map
	    PREVIOUS_PAGE = CURRENT_PAGE #found new page move along
	    CURRENT_PAGE = b_child.get_page_number()
	  else:
	    #print "First page found: "+str( d_child.get_page_number() )
	    FIRST_PAGE = b_child.get_page_number()
	    CURRENT_PAGE = b_child.get_page_number()
	    PREVIOUS_PAGE = ""

	
        #CURRENT_PAGE = b_child.get_page_number()
	#if CURRENT_PAGE != "":
	#  print "* ERROR --> PAGE DIVIDER FOUND IN BODY!!"
	#  print "Current Page: " + b_child.get_page_number()
        #build_body += b_child.MilestonetoHTML()
	
    #we have ended the tree travers... close the page map
    if translation:
      TRANS_PG_MAP.update_page(CURRENT_MS_KEY, CURRENT_PAGE, PREVIOUS_PAGE, "")
    else:
      MS_PG_MAP.update_page(CURRENT_MS_KEY, CURRENT_PAGE, PREVIOUS_PAGE, "")
    #print "build line page db!"
    #CURRENT_PAGE = ""
    translation = False

class div1(XElement):
  def Div1toHTML_paged(self, database=None, in_column=False):
    global HTML_STACK, CURRENT_FILE, MS_LPDB, MS_PG_MAP, CURRENT_MS_KEY    
    attrs = self.getAttributes()
    n = attrs.getFirst('n')
    _type = attrs.getFirst('type')
    org = attrs.getFirst('org')
    sample = attrs.getFirst('sample')
    continuation = attrs.getFirst('continue')
    if n == None:
      print "** ERROR div1 element with no end found please see data for unnatural div1 element **"
    #CURRENT_FILE.add_text("working on Div1!!!")
    if n != None and n.upper() != "BACK":
      HTML_STACK.push(['<span class="div1">', '</span>'])
      CURRENT_FILE.add_text('<span class="div1">')
      for d_child in self.getChildren():      
	
	#P
	#
        if d_child.__class__ == p:
	  #CURRENT_FILE.add_text("*** ERROR P ELEMENT FOUND IN DIV1 ELEMENT...PLEASE FIX DATA ***")
	  CURRENT_FILE.add_text(d_child.PtoHTML())
          #build_div1 += d_child.PtoHTML()
	#DIV2
	#
	elif d_child.__class__ == div2:
	  d_child.Div2toHTML_paged(database)
	  #CURRENT_FILE.add_text( "** WORKING ON DIV2 STILL! **" )
	  
	#LB
	#
        elif d_child.__class__ == lb:  #LINE BREAKS
          d_child.LBtoHTML_paged()
	#NOTE
	#
        elif d_child.__class__ == note: #NOTE POPUPS
          CURRENT_FILE.add_text(d_child.NotetoHTML())
	#MILESTONE
	#
        elif d_child.__class__ == milestone:
          if d_child.is_page_marker():
	    if CURRENT_FILE.is_name_set():
	      #print "DEBUG: FILE NAME IS SET!"
	      #end current page to start a new one
	      CURRENT_FILE.add_text(HTML_STACK.closing_contents()) #close open tags
	      #
	      # ADD PAGE NAVGATION HERE!!
	      #			    
	      #CURRENT_FILE.add_text( HTML_PAGE_CLOSE ) #close page
	      CURRENT_FILE.text_close(database)
              CURRENT_FILE.write()  #write the file	  
	    
	      #START NEW PAGE
	      CURRENT_FILE.set_filename(FILENAMES[CURRENT_MS_KEY], d_child.get_page_number())
	      #CURRENT_FILE.add_text( HTML_PAGE_OPEN )
	      CURRENT_FILE.text_open(database)
	      CURRENT_FILE.add_text(HTML_STACK.opening_contents())
	      #CURRENT_FILE.add_MS_header( database.get_MS_name( CURRENT_MS_KEY ) )
	      CURRENT_FILE.add_text(d_child.MilestonetoHTML(in_column))
	      #start new page
	    else:
	      #start new page
	      CURRENT_FILE.set_filename(FILENAMES[CURRENT_MS_KEY], d_child.get_page_number())
	      CURRENT_FILE.text_open(database)
	      #CURRENT_FILE.add_MS_header( database.get_MS_name( CURRENT_MS_KEY ) )
	      CURRENT_FILE.add_text(d_child.MilestonetoHTML(in_column))
	  else:
	    CURRENT_FILE.add_text(d_child.MilestonetoHTML(in_column))
            #build_div1 += d_child.MilestonetoHTML()
	#ADD
	#
        elif d_child.__class__ == add:
          CURRENT_FILE.add_text(d_child.AddtoHTML())
	#HI
	#
        elif d_child.__class__ == hi:
          CURRENT_FILE.add_text(d_child.HitoHTML1())
	#EXPAN
	#
        elif d_child.__class__ == expan:
	  CURRENT_FILE.add_text(d_child.ExpantoHTML())
	#DELL
	#
        elif d_child.__class__ == dell: #might need to change this..... not sure
	  CURRENT_FILE.add_text(d_child.DelltoHTML())
	#DAMAGE
	#
        elif d_child.__class__ == damage: 
	  CURRENT_FILE.add_text(d_child.DamagetoHTML())
	#SPACE
	#
        elif d_child.__class__ == space:
          CURRENT_FILE.add_text(d_child.SpacetoHTML())
        else:
          pass
      CURRENT_FILE.add_text(HTML_STACK.pop()[1]) #close tags and pull off stack
  
  def Div1toHTML_tpaged(self, database=None, in_column=False):
    print "** DIV1 TRANSLATION **"
    global HTML_STACK, CURRENT_FILE, MS_LPDB, MS_PG_MAP, CURRENT_MS_KEY    
    attrs = self.getAttributes()
    n = attrs.getFirst('n')
    _type = attrs.getFirst('type')
    org = attrs.getFirst('org')
    sample = attrs.getFirst('sample')
    continuation = attrs.getFirst('continue')
    if n == None:
      print "** ERROR div1 element with no end found please see data for unnatural div1 element **"
    #CURRENT_FILE.add_text("working on Div1!!!")
    if n != None and n.upper() != "BACK":
      HTML_STACK.push(['<span class="div1">', '</span>'])
      CURRENT_FILE.add_text('<span class="div1">')
      for d_child in self.getChildren():      
	
	#P
	#
        if d_child.__class__ == p:
	  #CURRENT_FILE.add_text("*** ERROR P ELEMENT FOUND IN DIV1 ELEMENT...PLEASE FIX DATA ***")
	  CURRENT_FILE.add_text(d_child.PtoHTML())
          #build_div1 += d_child.PtoHTML()
	#DIV2
	#
	elif d_child.__class__ == div2:
	  d_child.Div2toHTML_tpaged(database)
	  #CURRENT_FILE.add_text( "** WORKING ON DIV2 STILL! **" )
	  
	#LB
	#
        elif d_child.__class__ == lb:  #LINE BREAKS
          d_child.LBtoHTML_paged()
	#NOTE
	#
        elif d_child.__class__ == note: #NOTE POPUPS
          CURRENT_FILE.add_text(d_child.NotetoHTML())
	#MILESTONE
	#
        elif d_child.__class__ == milestone:
          if d_child.is_page_marker():
	    print "DIV1 CHILD PAGE MARKER!"
	    print "DIV1 CHILD PAGE MARKER CURRENT_MS_KEY: "+str(CURRENT_MS_KEY)
	    if CURRENT_FILE.is_name_set():
	      #print "DEBUG: FILE NAME IS SET!"
	      #end current page to start a new one
	      CURRENT_FILE.add_text(HTML_STACK.closing_contents()) #close open tags
	      #
	      # ADD PAGE NAVGATION HERE!!
	      #			    
	      #CURRENT_FILE.add_text( HTML_PAGE_CLOSE ) #close page
	      CURRENT_FILE.text_close(database)
              CURRENT_FILE.write()  #write the file	  
	    
	      #START NEW PAGE
	      CURRENT_FILE.set_filename(TRANS_FILENAMES[CURRENT_MS_KEY], d_child.get_page_number())
	      #CURRENT_FILE.add_text( HTML_PAGE_OPEN )
	      CURRENT_FILE.text_open(database)
	      CURRENT_FILE.add_text(HTML_STACK.opening_contents())
	      #CURRENT_FILE.add_MS_header( database.get_MS_name( CURRENT_MS_KEY ) )
	      CURRENT_FILE.add_text(d_child.MilestonetoHTML(in_column))
	      #start new page
	    else:
	      #start new page
	      CURRENT_FILE.set_filename(TRANS_FILENAMES[CURRENT_MS_KEY], d_child.get_page_number())
	      CURRENT_FILE.text_open(database)
	      #CURRENT_FILE.add_MS_header( database.get_MS_name( CURRENT_MS_KEY ) )
	      CURRENT_FILE.add_text(d_child.MilestonetoHTML(in_column))
	  else:
	    CURRENT_FILE.add_text(d_child.MilestonetoHTML(in_column))
            #build_div1 += d_child.MilestonetoHTML()
	#ADD
	#
        elif d_child.__class__ == add:
          CURRENT_FILE.add_text(d_child.AddtoHTML())
	#HI
	#
        elif d_child.__class__ == hi:
          CURRENT_FILE.add_text(d_child.HitoHTML1())
	#EXPAN
	#
        elif d_child.__class__ == expan:
	  CURRENT_FILE.add_text(d_child.ExpantoHTML())
	#DELL
	#
        elif d_child.__class__ == dell: #might need to change this..... not sure
	  CURRENT_FILE.add_text(d_child.DelltoHTML())
	#DAMAGE
	#
        elif d_child.__class__ == damage: 
	  CURRENT_FILE.add_text(d_child.DamagetoHTML())
	#SPACE
	#
        elif d_child.__class__ == space:
          CURRENT_FILE.add_text(d_child.SpacetoHTML())
        else:
          pass
      CURRENT_FILE.add_text(HTML_STACK.pop()[1]) #close tags and pull off stack

  def Div1toHTML(self, database=None):
    attrs = self.getAttributes()
    n = attrs.getFirst('n')
    _type = attrs.getFirst('type')
    org = attrs.getFirst('org')
    sample = attrs.getFirst('sample')
    build_div1 = '<span class="div1">'
    if n !="back":
      for d_child in self.getChildren():      
        #print d_child.__class__
        if d_child.__class__ == p:
          build_div1 += d_child.PtoHTML()
	elif d_child.__class__ == div2:
	  #print d_child.Div2toHTML()
	  build_div1 += d_child.Div2toHTML(database)
        elif d_child.__class__ == lb:
          build_div1 += d_child.LBtoHTML()
          #filler += " *LB CODE HERE* "
        elif d_child.__class__ == note:
          build_div1 += d_child.NotetoHTML()
          #filler += " *NOTE CODE HERE* "
        elif d_child.__class__ == milestone:
            #filler += " *NEED TO CODE MILESTONE* "
          build_div1 += d_child.MilestonetoHTML()
        elif d_child.__class__ == add:
           #filler += " *NEED TO CODE ADD* "
          build_div1 += d_child.AddtoHTML()
        elif d_child.__class__ == hi:
          #filler += " *NEED TO CODE HI* "
          build_div1 += d_child.HitoHTML1()
        elif d_child.__class__ == expan:
          build_div1 += d_child.ExpantoHTML()
          #filler += " *EPAN CODE HERE* "
        elif d_child.__class__ == dell: #might need to change this..... not sure
          #filler += " *NEED TO CODE DELL* "
          build_div1 += d_child.DelltoHTML()
        elif d_child.__class__ == damage:
          #filler += " *NEED TO CODE DAMAGE* "
          build_div1 += d_child.DamagetoHTML()
        elif d_child.__class__ == space:
          #filler += " *NEED TO CODE SPACE* "
          build_div1 += d_child.SpacetoHTML()
        else:
          pass
	  
    return build_div1 + '</span>'

  def get_lines_per_page(self, translation=False):
    #print "DIV2 translation: "+str( translation )
    global CURRENT_PAGE, CURRENT_MS_KEY, TRANS_LPDB, MS_LPDB, MS_PG_MAP, PREVIOUS_PAGE, LAST_PAGE, FIRST_PAGE
    child_number = 1
    for d_child in self.getChildren():
      #print str(child_number)+": "+str( d_child.name )
      child_number +=1
      if d_child.__class__ == milestone:
        if d_child.is_page_marker():
	  #print "CURRENT PAGE BEFORE ASSIGN: "+ CURRENT_PAGE
	  if CURRENT_PAGE != "":
	    #print "NOT FIRST PAGE!"
	    if translation:
	      TRANS_PG_MAP.update_page(CURRENT_MS_KEY, CURRENT_PAGE, PREVIOUS_PAGE, d_child.get_page_number())
	    else:
	      MS_PG_MAP.update_page(CURRENT_MS_KEY, CURRENT_PAGE, PREVIOUS_PAGE, d_child.get_page_number())#set last current page in page map
	    PREVIOUS_PAGE = CURRENT_PAGE #found new page move along
	    CURRENT_PAGE = d_child.get_page_number()
	  else:
	    #print "First page found: "+str( d_child.get_page_number() )
	    FIRST_PAGE = d_child.get_page_number()
	    CURRENT_PAGE = d_child.get_page_number()
	    PREVIOUS_PAGE = "" #set just in case :

	  #print "Current Page: " + d_child.get_page_number()
	  #print "CURRENT PAGE AFTER ASSIGN: "+ CURRENT_PAGE
      if d_child.__class__ == div2:
        #MS_LPDB[ CURRENT_MS_KEY ].append ( [ d_child.getLineNumberOnly(), CURRENT_PAGE ] )
         
        if translation:
	  TRANS_LPDB.add_line(d_child.getLineNumberOnly())
	else:
	  MS_LPDB.add_line(d_child.getLineNumberOnly())
        d_child.get_lines_per_page(translation)
	  
    translation = False    

    
class xref(XElement):
  def get(self):
    print "not yet"

class milestone(XElement): #specifies new page
  def MilestonetoHTML(self, in_column=False):
    attrs = self.getAttributes()
    n = attrs.getFirst('n')
    unit = attrs.getFirst('unit')
    if str(unit) == 'fol':
      return '<div class="pagemarker" title="Page '+enc(n)[0]+' starts here"><span class="innerpagemarker"><a name="'+enc(n)[0]+'">'+enc(n)[0]+'</a></span></div>'
    else:
      if not in_column:
        return '<div class="chaptermarker"><span class="innerchaptermarker"><a name="'+enc(n)[0]+'">'+enc(n)[0]+'</a></span></div>'
      else:
        return '<div class="in_column_chaptermarker"><span class="innerchaptermarker"><a name="'+enc(n)[0]+'">'+enc(n)[0]+'</a></span></div>' 
  def is_page_marker(self):
    attrs = self.getAttributes()
    n = attrs.getFirst('n')
    unit = attrs.getFirst('unit')
    if str(unit) == 'fol':
      return True
    else:
      return False

  def get_page_number(self):
    attrs = self.getAttributes()
    n = attrs.getFirst('n')
    unit = attrs.getFirst('unit')
    if str(unit) == 'fol':
      return str(enc(n)[0])
    else:
      return ""

class column(XElement):
  def ColumntoHTML(self, database=None):
    global HTML_STACK, CURRENT_FILE, MS_LPDB, MS_PG_MAP, CURRENT_MS_KEY
    HTML_STACK.push(['<table border="0" cellpadding="0" cellspacing="0" style="width: 100%;"><tr valign="top">', '</tr></table>'])
    CURRENT_FILE.add_text('<table border="0" cellpadding="0" cellspacing="0" style="width: 100%;"><tr valign="top">')
    for c_child in self.getChildren():
      if c_child.__class__ == col_left:
        c_child.Col_lefttoHTML(database)
      if c_child.__class__ == col_right:
        c_child.Col_righttoHTML(database)
    CURRENT_FILE.add_text(HTML_STACK.pop()[1])

class col_left(XElement):
  def Col_lefttoHTML(self, database=None):
    global HTML_STACK, CURRENT_FILE, MS_LPDB, MS_PG_MAP, CURRENT_MS_KEY
    HTML_STACK.push(['<td>', '</td><td width="20px">&nbsp;'])
    CURRENT_FILE.add_text('<td>')
    for c_child in self.getChildren():
      if c_child.__class__ == div1:
        #pass in column flag as true
        c_child.Div1toHTML_paged(database , True)
    CURRENT_FILE.add_text(HTML_STACK.pop()[1])

class col_right(XElement):
  def Col_righttoHTML(self, database=None):
    global HTML_STACK, CURRENT_FILE, MS_LPDB, MS_PG_MAP, CURRENT_MS_KEY
    HTML_STACK.push(['</td><td>', '</td>'])
    CURRENT_FILE.add_text('<td>')
    for c_child in self.getChildren():
      if c_child.__class__ == div1:
        #pass in column flag as true
        c_child.Div1toHTML_paged(database, True)
    CURRENT_FILE.add_text(HTML_STACK.pop()[1])

class div2(XElement):

  def Div2toHTML_tpaged(self, database=None):
    global HTML_STACK, CURRENT_FILE, TRANS_LPDB, MS_LPDB, MS_PG_MAP, CURRENT_MS_KEY 
    #print "** DIV2 TRANSLATION **"
    attrs = self.getAttributes()
    n = attrs.getFirst('n')
    _type = attrs.getFirst('type')
    org = attrs.getFirst('org')
    sample = attrs.getFirst('sample')
    continuation = attrs.getFirst('continue')
    #CURRENT_FILE.add_text("working on Div1!!!")
    if n.upper() != "BACK":
      HTML_STACK.push(['<span class="div2">', '</span>'])
      if continuation != 'true':
        CURRENT_FILE.add_text('<span class="div2">'+ self.lineNumber_tpaged(database)) #modify for lineNumber_paged!!!
      else:
        CURRENT_FILE.add_text('<span class="div2">')
      for d_child in self.getChildren():      
	
	#P
	#
        if d_child.__class__ == p:
	  #CURRENT_FILE.add_text("*** ERROR P ELEMENT FOUND IN DIV1 ELEMENT...PLEASE FIX DATA ***")
	  CURRENT_FILE.add_text(d_child.PtoHTML())
          #build_div1 += d_child.PtoHTML()
	#LB
	#
        elif d_child.__class__ == lb:  #LINE BREAKS
          d_child.LBtoHTML_paged()
	#NOTE
	#
        elif d_child.__class__ == note: #NOTE POPUPS
          CURRENT_FILE.add_text(d_child.NotetoHTML())
	#MILESTONE
	#
        elif d_child.__class__ == milestone:
          if d_child.is_page_marker():
	    if CURRENT_FILE.is_name_set():
	      #print "DEBUG: FILE NAME IS SET!"
	      #end current page to start a new one
	      CURRENT_FILE.add_text(HTML_STACK.closing_contents()) #close open tags
	      #
	      # ADD PAGE NAVGATION HERE!!
	      #			    
	      #CURRENT_FILE.add_text( HTML_PAGE_CLOSE ) #close page
	      CURRENT_FILE.text_close(database)
              CURRENT_FILE.write()  #write the file	  
	    
	      #START NEW PAGE
	      CURRENT_FILE.set_filename(TRANS_FILENAMES[CURRENT_MS_KEY], d_child.get_page_number())
	      #CURRENT_FILE.add_text( HTML_PAGE_OPEN )
	      CURRENT_FILE.text_open(database)
	      CURRENT_FILE.add_text(HTML_STACK.opening_contents())    
	      #CURRENT_FILE.add_MS_header( database.get_MS_name( CURRENT_MS_KEY ) )
	      CURRENT_FILE.add_text(d_child.MilestonetoHTML())
	      #start new page
	    else:
	      #start new page
	      CURRENT_FILE.set_filename(TRANS_FILENAMES[CURRENT_MS_KEY], d_child.get_page_number())
	      CURRENT_FILE.text_open(database)
	      #CURRENT_FILE.add_MS_header( database.get_MS_name( CURRENT_MS_KEY ) )
	      CURRENT_FILE.add_text(d_child.MilestonetoHTML())          
            #build_div1 += d_child.MilestonetoHTML()
	#ADD
	#
	  else:
	    CURRENT_FILE.add_text(d_child.MilestonetoHTML())
        elif d_child.__class__ == add:
          CURRENT_FILE.add_text(d_child.AddtoHTML())
	#HI
	#
        elif d_child.__class__ == hi:
          CURRENT_FILE.add_text(d_child.HitoHTML1())
	#EXPAN
	#
        elif d_child.__class__ == expan:
	  CURRENT_FILE.add_text(d_child.ExpantoHTML())
	#DELL
	#
        elif d_child.__class__ == dell: #might need to change this..... not sure
	  CURRENT_FILE.add_text(d_child.DelltoHTML())
	#DAMAGE
	#
        elif d_child.__class__ == damage: 
	  CURRENT_FILE.add_text(d_child.DamagetoHTML())
	#SPACE
	#
        elif d_child.__class__ == space:
          CURRENT_FILE.add_text(d_child.SpacetoHTML())
        else:
	  print "unsupported tag: "+str(d_child.__class__)

      CURRENT_FILE.add_text(HTML_STACK.pop()[1]) #close tags and pull off stack
  
  def Div2toHTML_paged(self, database=None):
    global HTML_STACK, CURRENT_FILE, TRANS_LPDB, MS_LPDB, MS_PG_MAP, CURRENT_MS_KEY    
    attrs = self.getAttributes()
    n = attrs.getFirst('n')
    _type = attrs.getFirst('type')
    org = attrs.getFirst('org')
    sample = attrs.getFirst('sample')
    continuation = attrs.getFirst('continue')
    #CURRENT_FILE.add_text("working on Div1!!!")
    if n.upper() != "BACK":
      HTML_STACK.push(['<span class="div2">', '</span>'])
      if continuation != 'true':
        CURRENT_FILE.add_text('<span class="div2">'+ self.lineNumber_paged(database)) #modify for lineNumber_paged!!!
      else:
        CURRENT_FILE.add_text('<span class="div2">')
      for d_child in self.getChildren():      
	
	#P
	#
        if d_child.__class__ == p:
	  #CURRENT_FILE.add_text("*** ERROR P ELEMENT FOUND IN DIV1 ELEMENT...PLEASE FIX DATA ***")
	  CURRENT_FILE.add_text(d_child.PtoHTML())
          #build_div1 += d_child.PtoHTML()
	#LB
	#
        elif d_child.__class__ == lb:  #LINE BREAKS
          d_child.LBtoHTML_paged()
	#NOTE
	#
        elif d_child.__class__ == note: #NOTE POPUPS
          CURRENT_FILE.add_text(d_child.NotetoHTML())
	#MILESTONE
	#
        elif d_child.__class__ == milestone:
          if d_child.is_page_marker():
	    if CURRENT_FILE.is_name_set():
	      #print "DEBUG: FILE NAME IS SET!"
	      #end current page to start a new one
	      CURRENT_FILE.add_text(HTML_STACK.closing_contents()) #close open tags
	      #
	      # ADD PAGE NAVGATION HERE!!
	      #			    
	      #CURRENT_FILE.add_text( HTML_PAGE_CLOSE ) #close page
	      CURRENT_FILE.text_close(database)
              CURRENT_FILE.write()  #write the file	  
	    
	      #START NEW PAGE
	      CURRENT_FILE.set_filename(FILENAMES[CURRENT_MS_KEY], d_child.get_page_number())
	      #CURRENT_FILE.add_text( HTML_PAGE_OPEN )
	      CURRENT_FILE.text_open(database)
	      CURRENT_FILE.add_text(HTML_STACK.opening_contents())    
	      #CURRENT_FILE.add_MS_header( database.get_MS_name( CURRENT_MS_KEY ) )
	      CURRENT_FILE.add_text(d_child.MilestonetoHTML())
	      #start new page
	    else:
	      #start new page
	      CURRENT_FILE.set_filename(FILENAMES[CURRENT_MS_KEY], d_child.get_page_number())
	      CURRENT_FILE.text_open(database)
	      #CURRENT_FILE.add_MS_header( database.get_MS_name( CURRENT_MS_KEY ) )
	      CURRENT_FILE.add_text(d_child.MilestonetoHTML())          
            #build_div1 += d_child.MilestonetoHTML()
	#ADD
	#
	  else:
	    CURRENT_FILE.add_text(d_child.MilestonetoHTML())
        elif d_child.__class__ == add:
          CURRENT_FILE.add_text(d_child.AddtoHTML())
	#HI
	#
        elif d_child.__class__ == hi:
          CURRENT_FILE.add_text(d_child.HitoHTML1())
	#EXPAN
	#
        elif d_child.__class__ == expan:
	  CURRENT_FILE.add_text(d_child.ExpantoHTML())
	#DELL
	#
        elif d_child.__class__ == dell: #might need to change this..... not sure
	  CURRENT_FILE.add_text(d_child.DelltoHTML())
	#DAMAGE
	#
        elif d_child.__class__ == damage: 
	  CURRENT_FILE.add_text(d_child.DamagetoHTML())
	#SPACE
	#
        elif d_child.__class__ == space:
          CURRENT_FILE.add_text(d_child.SpacetoHTML())
        else:
          pass
      CURRENT_FILE.add_text(HTML_STACK.pop()[1]) #close tags and pull off stack
	  
  def get_lines_per_page(self, translation=False):
   global CURRENT_PAGE, CURRENT_MS_KEY, TRANS_LPDB, MS_LPDB, TRANS_PG_MAP, MS_PG_MAP, PREVIOUS_PAGE, LAST_PAGE, FIRST_PAGE
   child_number = 1
   #print "DIV2 TRANSLATION SETTING: "+str( translation )
   for d_child in self.getChildren():
     #print str(child_number)+": "+str( d_child.name )
     child_number +=1
     if d_child.__class__ == milestone:
       if d_child.is_page_marker():
         #print "CURRENT PAGE BEFORE ASSIGN: "+ CURRENT_PAGE
         if CURRENT_PAGE != "":
	   #print "NOT FIRST PAGE!"	
           if translation:
	     TRANS_PG_MAP.update_page(CURRENT_MS_KEY, CURRENT_PAGE, PREVIOUS_PAGE, d_child.get_page_number())
	   else:
	     MS_PG_MAP.update_page(CURRENT_MS_KEY, CURRENT_PAGE, PREVIOUS_PAGE, d_child.get_page_number()) #set last current page in page map
	   PREVIOUS_PAGE = CURRENT_PAGE #found new page move along
	   CURRENT_PAGE = d_child.get_page_number()
	 else:
	   #print "First page found: "+str( d_child.get_page_number() )
	   FIRST_PAGE = d_child.get_page_number()
	   PREVIOUS_PAGE = "" #set just in case :)
	   CURRENT_PAGE = d_child.get_page_number()

	 #print "Current Page: " + d_child.get_page_number() 
   translation = False

  def get_lines_per_page2(self):
    global CURRENT_PAGE
    child_number = 1
    for d_child in self.getChildren():
      print "\t\t"+str(child_number)+": "+str(d_child.name)
      child_number +=1
      if d_child.__class__ == milestone:
        if d_child.is_page_marker():
	  CURRENT_PAGE = d_child.get_page_number()
	  print "\t\tPage found: " + d_child.get_page_number()

  def getLineNumberOnly(self):
    return self.getAttributes().getFirst('n')
  def lineNumberorig(self):
    return '<span class="" style="color: red; position: relative; font-size: 11px; cursor: default;">'+self.getAttributes().getFirst('n')+'<![CDATA[&nbsp;]]></span>'
  ################

  def lineNumber_tpaged(self, database=None, pagetranslation=False):
    global MS_LPDB
    no_translation = False
    other_translation = False
    no_other_versions = False
    cur_line_number = self.getAttributes().getFirst('n')
    MS_key = cur_line_number[0]
    #translation = database.get_translation(MS_key, cur_line_number)
    get_translation = database.get_translation(cur_line_number, True)
    translation = "[<b style=\\'font-size: 14px;\\'>Translated from the text of MS "+get_translation[0]+"</b>]<br/><br/>"+get_translation[1]
    search_line = cur_line_number[1:len(cur_line_number)]
    line_in_other_MSS = []

    for key in database.manuscripts: # find line numbers in other docs      
      #if MS_key != key: #don't add our current document to search        #search for line        
      if database.manuscripts[key]['document'].has_line(search_line):          
        key_found = key+search_line          
        line_in_other_MSS.append(key_found)
    
    
#
#BUILD MENU
#
    
    menu =  "<ul class=\\'LineNumberMenu\\' style=\\'font-size: 12px;\\'>"

    if len(line_in_other_MSS) == 0:
      no_other_versions = True
   # if True:  #put this here because I didn't want to re-align all the code :)
   #   menu += "<li><div><div><center style=\\'position: relative; top: 2px;\\'>Translate canon</center></div></div>"
    #insert Quick Translation text here
   #   menu += "<div class=\\'quicktranslation\\'><div>"
   #   menu += "<table cellspacing=\\'0\\'style=\\' height: 100%; width: 100%; padding:0; background-color: #003399;\\'><tr><td style=\\'height: 10px; background-color: #003399; font-size: 13px;  font-weight: bold; color: #ffffff;\\'>&nbsp;"+cur_line_number+"</td></tr>"    
   #   menu += "<tr style=\\'background-color: #003399;\\'><td valign=\\'top\\'style=\\'font-size: 15px;\\'><table style=\\'min-width: 400px; background-color: #E5ECFF;\\'><tr><td width=400px>"+translation+"</td></tr></table></td></tr>"
      #END QUICK TRANSLATION CODE
   #   menu +=  "</div></div>"
   #   menu += '</li>'
    
      #menu += "<li><div><div><center style=\\'position: relative; top: 2px;\\'>No Translation</center></div></div></li>"
    #menu += "  <li><div><div><center style=\\'position: relative; top: 2px;\\'>Other options<span style=\\'position: absolute; right: 4px; top: -1px; font-weight: bold; font-size: 12px;\\'>></span></center></div></div>"
    #add sub menu here
    #menu += '    <ul>'
    menu += "  <li title=\\'View this manuscript and the translation.\\'><div><div><center style=\\' position: relative; top: 2px; cursor: pointer;\\' onclick=\\'javascript:open_new_window(url2, name);\\'>View text + translation</center></div></div></li>"
    #menu += "     <li title=\\'View translation of this manuscript only.\\'><div><div><center style=\\' position: relative; top: 2px;\\'>View translation alone</center></div></div></li>"
    #menu += '   </ul>'
    #menu += "  </li>"
    #menu += "  <li bgcolor=\\'black\\' title=\\'View other manuscripts where this canon is also found.\\'><div><div><center style=\\'position: relative; top: 2px;\\'>View other versions<span style=\\'position: absolute; right: 4px; top: -1px; font-weight: bold; font-size: 12px;\\'>></span></center></div></div>"
    #add sub menu here
    #menu += '    <ul>'
    #if len(line_in_other_MSS) > 0:
      #menu += "      <li title=\\'View all versions of canon "+cur_line_number+" in one view.\\'><div><div><center style=\\'position: relative; top: 2px; cursor: pointer\\' onclick=\\'javascript:open_new_window(url, name);\\'>View all versions</center></div></div>"
      #menu += "</li>"
    #else:
      #menu += "      <li title=\\'Other versions of this canon were not found in other manuscripts.\\'><div><div><center style=\\'position: relative; top: 2px;\\'>Not available</center></div></div>"
    #menu += '  </li>'
    if len(line_in_other_MSS) > 0:
      menu += "<li title=\\'Go to another version of this text.\\'><div><div><center style=\\'position: relative; top: 2px;\\'>Go to<span style=\\'position: absolute; right: 4px; top: -1px; font-weight: bold; font-size: 12px;\\'>></span></center></div></div>"
      menu += '  <ul>'      
      for line in line_in_other_MSS:
        tempname = FILENAMES[ line[0] ].split('.')	
	#filename = tempname[0]+"_"+page+"."+name[1]
	page = None
	#print translation
	if pagetranslation:
	  page = TRANS_LPDB.get_page(line)
	else:
	  page = MS_LPDB.get_page(line)
	filename = tempname[0]+"_"+page+"."+tempname[1]
	#print "Found line "+line+" in file "+filename
	#filename = ""
	menu += "    <li title=\\'Canon "+line[1:len(line)]+" is also found in manuscript "+line[0]+".\\'><div><div><center style=\\'position: relative; top: 2px;\\'><a class=\\'menulink\\'  href=\\'"+filename+"#"+line+"\\'>"+line+"</a></center></div></div></li>"
	
      menu += '  </ul>'
      menu += "</li>"
    menu += '</ul>'
    #menu += '  </li>'
    #menu += '</ul>'
   
    
    title = "<table class=\\'title\\'style=\\'cursor: default; width: 100%; font-size: 9px; color: white;\\'><tr><td>"+cur_line_number+"</td><td align=\\'right\\'>"+"<table class=\\'close\\' border=\\'0\\' style=\\' font-size: 11px; border-style: solid; border: 1px; color: white;\\'><tr><td title=\\'Click to close Menu\\'>&nbsp;X&nbsp;</td></tr></table></td></tr></table>"
    if no_translation == False or no_other_versions == False:
      #return line_table+'<span onmouseover="javascript:menu= new getObj(\''+cur_line_number+'\')"><span id="lineno" onmouseover=";this.T_OFFSETY=-10;this.T_OFFSETX=-32;this.T_FONTSIZE=\'10pt\';this.T_WIDTH=165;this.T_STICKY=true;this.T_TITLE=\''+title+'\'; return escape('+"'"+menu+"'"+')"><a name="'+cur_line_number+'">'+cur_line_number+'</a></span></span>'
      #return '<span id="lineno" onmouseover=";this.T_OFFSETY=-10;this.T_OFFSETX=-32;this.T_FONTSIZE=\'10pt\';this.T_WIDTH=165;this.T_STICKY=true;this.T_TITLE=\''+title+'\'; return escape('+"'"+menu+"'"+')"><a name="'+cur_line_number+'">'+cur_line_number+'</a></span>'
      return '<br/><span onmouseover="javascript:url=\'line_table/'+cur_line_number[1:len(cur_line_number)]+'.html\';javascript:url2=\'translation_table/'+cur_line_number+'.html\'; javascript:name=\'View all versions of canon '+cur_line_number+'\';"><span style="color: red; position: relative; font-size: 11px; cursor: default;" onmouseover=";this.T_OFFSETY=-10;this.T_OFFSETX=-32;this.T_FONTSIZE=\'10pt\';this.T_WIDTH=165;this.T_STICKY=true;this.T_TITLE=\''+title+'\'; return escape('+"'"+menu+"'"+')"><a name="'+cur_line_number+'">'+cur_line_number+'</a></span></span>'
    else:
      return '<br/><span style="color: red; position: relative; font-size: 11px; cursor: default;" onmouseover="this.T_FONTSIZE=\'10pt\';this.T_TITLE=\''+cur_line_number+'\'; return escape(\'No translations or other versions of this canon exist in any manuscript.\')"><a name="'+cur_line_number+'">'+cur_line_number+'</a></span>'

  ################
  
  def lineNumber_paged(self, database=None, pagetranslation=False):
    global MS_LPDB
    no_translation = False
    other_translation = False
    no_other_versions = False
    cur_line_number = self.getAttributes().getFirst('n')
    MS_key = cur_line_number[0]
    #translation = database.get_translation(MS_key, cur_line_number)
    get_translation = database.get_translation(cur_line_number, True)
    translation = "[<b style=\\'font-size: 14px;\\'>Translated from the text of MS "+get_translation[0]+"</b>]<br/><br/>"+get_translation[1]
    search_line = cur_line_number[1:len(cur_line_number)]
    line_in_other_MSS = []

    for key in database.manuscripts: # find line numbers in other docs      
      if MS_key != key: #don't add our current document to search        #search for line        
        if database.manuscripts[key]['document'].has_line(search_line):          
          key_found = key+search_line          
          line_in_other_MSS.append(key_found)
    
    
#
#BUILD MENU
#
    
    menu =  "<ul class=\\'LineNumberMenu\\' style=\\'font-size: 12px;\\'>"

    if len(line_in_other_MSS) == 0:
      no_other_versions = True
    if True:  #put this here because I didn't want to re-align all the code :)
      menu += "  <li><div><div><center style=\\'position: relative; top: 2px;\\'>Translate canon</center></div></div>"
    #insert Quick Translation text here
      menu += "<div class=\\'quicktranslation\\'><div>"
      menu += "<table cellspacing=\\'0\\'style=\\' height: 100%; width: 100%; padding:0; background-color: #003399;\\'><tr><td style=\\'height: 10px; background-color: #003399; font-size: 13px;  font-weight: bold; color: #ffffff;\\'>&nbsp;"+cur_line_number+"</td></tr>"    
      menu += "<tr style=\\'background-color: #003399;\\'><td valign=\\'top\\'style=\\'font-size: 15px;\\'><table style=\\'min-width: 400px; background-color: #E5ECFF;\\'><tr><td width=400px>"+translation+"</td></tr></table></td></tr>"
      #END QUICK TRANSLATION CODE
      menu +=  "</div></div>"
      menu += '</li>'
    
      #menu += "<li><div><div><center style=\\'position: relative; top: 2px;\\'>No Translation</center></div></div></li>"
    menu += "  <li><div><div><center style=\\'position: relative; top: 2px;\\'>Other options<span style=\\'position: absolute; right: 4px; top: -1px; font-weight: bold; font-size: 12px;\\'>></span></center></div></div>"
    #add sub menu here
    menu += '    <ul>'
    menu += "     <li title=\\'View this manuscript and the translation.\\'><div><div><center style=\\' position: relative; top: 2px; cursor: pointer;\\' onclick=\\'javascript:open_new_window(url2, name);\\'>View text + translation</center></div></div></li>"
    #print database.find_translation_location( cur_line_number )
    
        
    trans_ms_key = TRANS_LPDB.get_key_of_trans_map(cur_line_number)
    if trans_ms_key != 'Not Found!':
      #print cur_line_number
      #print trans_ms_key
      tfilename = TRANS_FILENAMES[ trans_ms_key].split('.')
      print "("+str(cur_line_number)+")MAKE MENU DEBUG: "+str(trans_ms_key)
      print "("+str(cur_line_number)+")MAKE MENU DEBUG: "+str(cur_line_number)
      pg = TRANS_LPDB.get_tpage(trans_ms_key, cur_line_number)
      tfile = tfilename[0]+"_"+str(pg)+"."+tfilename[1]
      print "("+str(cur_line_number)+")TRANSLATION FILE (DEBUG): "+str(tfilename[0]+"_"+str(pg)+tfilename[1])
      #print str(cur_line_number), ":", str(tfilename[0]+"_"+str(pg)+"."+tfilename[1])
      citationDict[str(cur_line_number)] = CURRENT_FILE.get_filename()
      menu += "     <li title=\\'View translation of this manuscript only.\\'><div><div><center style=\\' position: relative; top: 2px;\\'><a href=\\'"+tfile+"#"+trans_ms_key[0]+cur_line_number[1:len(cur_line_number)]+"\\'>View translation alone</a></center></div></div></li>"
    #else:  
    #  menu += "     <li title=\\'non translation.\\'><div><div><center style=\\' position: relative; top: 2px;\\'>View translation alone(NF)</center></div></div></li>"
    menu += '   </ul>'
    menu += "  </li>"
    menu += "  <li bgcolor=\\'black\\' title=\\'View other manuscripts where this canon is also found.\\'><div><div><center style=\\'position: relative; top: 2px;\\'>View other versions<span style=\\'position: absolute; right: 4px; top: -1px; font-weight: bold; font-size: 12px;\\'>></span></center></div></div>"
    #add sub menu here
    menu += '    <ul>'
    if len(line_in_other_MSS) > 0:
      menu += "      <li title=\\'View all versions of canon "+cur_line_number+" in one view.\\'><div><div><center style=\\'position: relative; top: 2px; cursor: pointer\\' onclick=\\'javascript:open_new_window(url, name);\\'>View all versions</center></div></div>"
      menu += "</li>"
    else:
      menu += "      <li title=\\'Other versions of this canon were not found in other manuscripts.\\'><div><div><center style=\\'position: relative; top: 2px;\\'>Not available</center></div></div>"
    menu += '      </li>'
    if len(line_in_other_MSS) > 0:
      menu += "      <li title=\\'Go to another version of this text.\\'><div><div><center style=\\'position: relative; top: 2px;\\'>Go to<span style=\\'position: absolute; right: 4px; top: -1px; font-weight: bold; font-size: 12px;\\'>></span></center></div></div>"
      menu += '        <ul>'      
      for line in line_in_other_MSS:
        tempname = FILENAMES[ line[0] ].split('.')	
	#filename = tempname[0]+"_"+page+"."+name[1]
	page = None
	#print translation
	if pagetranslation: #only used when generating a full translation page
	  page = TRANS_LPDB.get_page(line)
	else:
	  #print "line_debug: "+str( line )
	  #print "page_debug: "+str( MS_LPDB.get_page( line ) ) 
	  page = MS_LPDB.get_page(line)

	filename = tempname[0]+"_"+page+"."+tempname[1]
	#print "Found line "+line+" in file "+filename
	#filename = ""
	menu += "          <li title=\\'Canon "+line[1:len(line)]+" is also found in manuscript "+line[0]+".\\'><div><div><center style=\\'position: relative; top: 2px;\\'><a class=\\'menulink\\'  href=\\'"+filename+"#"+line+"\\'>"+line+"</a></center></div></div></li>"
	
      menu += '        </ul>'
      menu += "      </li>"
    menu += '    </ul>'
    menu += '  </li>'
    menu += '</ul>'
    
    title = "<table class=\\'title\\'style=\\'cursor: default; width: 100%; font-size: 9px; color: white;\\'><tr><td>"+cur_line_number+"</td><td align=\\'right\\'>"+"<table class=\\'close\\' border=\\'0\\' style=\\' font-size: 11px; border-style: solid; border: 1px; color: white;\\'><tr><td title=\\'Click to close Menu\\'>&nbsp;X&nbsp;</td></tr></table></td></tr></table>"
    if no_translation == False or no_other_versions == False:
      #return line_table+'<span onmouseover="javascript:menu= new getObj(\''+cur_line_number+'\')"><span id="lineno" onmouseover=";this.T_OFFSETY=-10;this.T_OFFSETX=-32;this.T_FONTSIZE=\'10pt\';this.T_WIDTH=165;this.T_STICKY=true;this.T_TITLE=\''+title+'\'; return escape('+"'"+menu+"'"+')"><a name="'+cur_line_number+'">'+cur_line_number+'</a></span></span>'
      #return '<span id="lineno" onmouseover=";this.T_OFFSETY=-10;this.T_OFFSETX=-32;this.T_FONTSIZE=\'10pt\';this.T_WIDTH=165;this.T_STICKY=true;this.T_TITLE=\''+title+'\'; return escape('+"'"+menu+"'"+')"><a name="'+cur_line_number+'">'+cur_line_number+'</a></span>'
      return '<span onmouseover="javascript:url=\'line_table/'+cur_line_number[1:len(cur_line_number)]+'.html\';javascript:url2=\'translation_table/'+cur_line_number+'.html\'; javascript:name=\'View all versions of canon '+cur_line_number+'\';"><span style="color: red; position: relative; font-size: 11px; cursor: default;" onmouseover=";this.T_OFFSETY=-10;this.T_OFFSETX=-32;this.T_FONTSIZE=\'10pt\';this.T_WIDTH=165;this.T_STICKY=true;this.T_TITLE=\''+title+'\'; return escape('+"'"+menu+"'"+')"><a name="'+cur_line_number+'">'+cur_line_number+'</a></span></span>'
    else:
      return '<span style="color: red; position: relative; font-size: 11px; cursor: default;" onmouseover="this.T_FONTSIZE=\'10pt\';this.T_TITLE=\''+cur_line_number+'\'; return escape(\'No translations or other versions of this canon exist in any manuscript.\')"><a name="'+cur_line_number+'">'+cur_line_number+'</a></span>'

    
  def lineNumber(self, database=None):    
    no_translation = False
    other_translation = False
    no_other_versions = False
    cur_line_number = self.getAttributes().getFirst('n')
    MS_key = cur_line_number[0]
    #translation = database.get_translation(MS_key, cur_line_number)
    get_translation = database.get_translation(cur_line_number, True)
    translation = "[<b style=\\'font-size: 14px;\\'>Translated from the text of MS "+get_translation[0]+"</b>]<br/><br/>"+get_translation[1]
    search_line = cur_line_number[1:len(cur_line_number)]
    line_in_other_MSS = []

    for key in database.manuscripts: # find line numbers in other docs      
      if MS_key != key: #don't add our current document to search        #search for line        
        if database.manuscripts[key]['document'].has_line(search_line):          
          key_found = key+search_line          
          line_in_other_MSS.append(key_found)
    
    
#
#BUILD MENU
#
    
    menu =  "<ul class=\\'LineNumberMenu\\' style=\\'font-size: 12px;\\'>"

    if len(line_in_other_MSS) == 0:
      no_other_versions = True
    if True:  #put this here because I didn't want to re-align all the code :)
      menu += "  <li><div><div><center style=\\'position: relative; top: 2px;\\'>Translate canon</center></div></div>"
    #insert Quick Translation text here
      menu += "<div class=\\'quicktranslation\\'><div>"
      menu += "<table cellspacing=\\'0\\'style=\\' height: 100%; width: 100%; padding:0; background-color: #003399;\\'><tr><td style=\\'height: 10px; background-color: #003399; font-size: 13px;  font-weight: bold; color: #ffffff;\\'>&nbsp;"+cur_line_number+"</td></tr>"    
      menu += "<tr style=\\'background-color: #003399;\\'><td valign=\\'top\\'style=\\'font-size: 15px;\\'><table style=\\'min-width: 400px; background-color: #E5ECFF;\\'><tr><td width=400px>"+translation+"</td></tr></table></td></tr>"
      #END QUICK TRANSLATION CODE
      menu +=  "</div></div>"
      menu += '</li>'
    
      #menu += "<li><div><div><center style=\\'position: relative; top: 2px;\\'>No Translation</center></div></div></li>"
    menu += "  <li><div><div><center style=\\'position: relative; top: 2px;\\'>Translate whole text<span style=\\'position: absolute; right: 4px; top: -1px; font-weight: bold; font-size: 12px;\\'>></span></center></div></div>"
    #add sub menu here
    menu += '    <ul>'
    menu += "     <li title=\\'View this manuscript and the translation.\\'><div><div><center style=\\' position: relative; top: 2px;\\' onclick=\\'javascript:open_new_window(url2, name);\\'>View text + translation</center></div></div></li>"
    menu += "     <li title=\\'View translation of this manuscript only.\\'><div><div><center style=\\' position: relative; top: 2px;\\'>View translation alone</center></div></div></li>"
    menu += '   </ul>'
    menu += "  </li>"
    menu += "  <li bgcolor=\\'black\\' title=\\'View other manuscripts where this canon is also found.\\'><div><div><center style=\\'position: relative; top: 2px;\\'>View other versions<span style=\\'position: absolute; right: 4px; top: -1px; font-weight: bold; font-size: 12px;\\'>></span></center></div></div>"
    #add sub menu here
    menu += '    <ul>'
    if len(line_in_other_MSS) > 0:
      version_table = "<table style=\\'background-color: green; width: 400px; height: 400px;\\'><tr><td>&nbsp;</td></tr></table>"
                      
                      
      menu += "      <li title=\\'View all versions of canon "+cur_line_number+" in one view.\\'><div><div><center style=\\'position: relative; top: 2px; cursor: pointer\\' onclick=\\'javascript:open_new_window(url, name);\\'>View all versions</center></div></div>"
      #menu += "<div id=\\'alltranslation\\'>"+version_table+"</div>"
      menu += "</li>"
      #menu += "      <li title=\\'View this manuscript and one other side-by-side.\\'><div><div><center style=\\'position: relative; top: 2px;\\'>View this version and<span style=\\'position: absolute; right: 4px; top: -1px; font-weight: bold; font-size: 12px;\\'>></span></center></div></div>"
    #add sub sub menu here
      #menu += '        <ul>'
    #if len(line_in_other_MSS) > 0:
      #for line in line_in_other_MSS:
      #menu += "          <li><div><div><center style=\\'position: relative; top: 2px;\\'>LINE #</center></div></div></li>"
        #menu += "          <li title=\\'Canon "+line[1:len(line)]+" is also found in manuscript "+line[0]+".\\'><div><div><center style=\\'position: relative; top: 2px;\\'><a class=\\'menulink\\'>"+line+"</a></center></div></div></li>"
      
      #menu += '        </ul>'
    else:
      menu += "      <li title=\\'Other versions of this canon were not found in other manuscripts.\\'><div><div><center style=\\'position: relative; top: 2px;\\'>Not available</center></div></div>"
    menu += '      </li>'
    if len(line_in_other_MSS) > 0:
      menu += "      <li title=\\'Go to another version of this text.\\'><div><div><center style=\\'position: relative; top: 2px;\\'>Go to<span style=\\'position: absolute; right: 4px; top: -1px; font-weight: bold; font-size: 12px;\\'>></span></center></div></div>"
      menu += '        <ul>'      
      for line in line_in_other_MSS:
	
        menu += "          <li title=\\'Canon "+line[1:len(line)]+" is also found in manuscript "+line[0]+".\\'><div><div><center style=\\'position: relative; top: 2px;\\'><a class=\\'menulink\\'  href=\\'"+FILENAMES[line[0]]+"#"+line+"\\'>"+line+"</a></center></div></div></li>"
	
      menu += '        </ul>'
      menu += "      </li>"
    menu += '    </ul>'
    menu += '  </li>'
    menu += '</ul>'
   
    
    title = "<table class=\\'title\\'style=\\'cursor: default; width: 100%; font-size: 9px; color: white;\\'><tr><td>"+cur_line_number+"</td><td align=\\'right\\'>"+"<table class=\\'close\\' border=\\'0\\' style=\\' font-size: 11px; border-style: solid; border: 1px; color: white;\\'><tr><td title=\\'Click to close Menu\\'>&nbsp;X&nbsp;</td></tr></table></td></tr></table>"

    if no_translation == False or no_other_versions == False:
      #return line_table+'<span onmouseover="javascript:menu= new getObj(\''+cur_line_number+'\')"><span id="lineno" onmouseover=";this.T_OFFSETY=-10;this.T_OFFSETX=-32;this.T_FONTSIZE=\'10pt\';this.T_WIDTH=165;this.T_STICKY=true;this.T_TITLE=\''+title+'\'; return escape('+"'"+menu+"'"+')"><a name="'+cur_line_number+'">'+cur_line_number+'</a></span></span>'
      #return '<span id="lineno" onmouseover=";this.T_OFFSETY=-10;this.T_OFFSETX=-32;this.T_FONTSIZE=\'10pt\';this.T_WIDTH=165;this.T_STICKY=true;this.T_TITLE=\''+title+'\'; return escape('+"'"+menu+"'"+')"><a name="'+cur_line_number+'">'+cur_line_number+'</a></span>'
      return '<span onmouseover="javascript:url=\'line_table/'+cur_line_number[1:len(cur_line_number)]+'.html\';javascript:url2=\'translation_table/'+cur_line_number+'.html\'; javascript:name=\'View all versions of canon '+cur_line_number+'\';"><span style="color: red; position: relative; font-size: 11px; cursor: default;" onmouseover=";this.T_OFFSETY=-10;this.T_OFFSETX=-32;this.T_FONTSIZE=\'10pt\';this.T_WIDTH=165;this.T_STICKY=true;this.T_TITLE=\''+title+'\'; return escape('+"'"+menu+"'"+')"><a name="'+cur_line_number+'">'+cur_line_number+'</a></span></span>'
    else:
      return '<span style="color: red; position: relative; font-size: 11px; cursor: default;" onmouseover="this.T_FONTSIZE=\'10pt\';this.T_TITLE=\''+cur_line_number+'\'; return escape(\'No translations or other versions of this canon exist in any manuscript.\')"><a name="'+cur_line_number+'">'+cur_line_number+'</a></span>'

  def getDiv2(self, method):
    if method == "byline":
      return self.getDiv2byline()
    if method == "native":
      return self.getDiv2native()

  def getDiv2native(self):
    atts = self.getAttributes()
    lineno = atts.getFirst('n')
    d_children = self.getChildren()
    build_div2 = "" #we will use this to build our div2 structure and return it
    for d_child in d_children:
      if d_child.__class__ == lb:
        build_div2 += "<br>"
      elif d_child.__class__ == p:
        build_div2 += "ELEMENT P"
    return build_div2

  def Div2toHTML(self, database=None, show_line_number=True):
    atts = self.getAttributes()
    lineno = atts.getFirst('n')
    d_children = self.getChildren()
    temp = self.getText()
    filler = ""
    #begin = ""
    end = ""
    #print "TEMP: " + temp
    #for x in self.getChildren():
    #  print x.__class__

    #linenumber w/ out menu
    #build_div2 = '<span class="div2">'+ self.lineNumberorig()

    #linenumber w/ menu
    build_div2 = '<span class="div2">' #+ self.lineNumber(database)
    if show_line_number:
      build_div2 += self.lineNumber(database)
    
    
    for d_child in self.getChildren():
      pos = temp.find('<-*->')
      #print "DEBUG: "+temp
      filler = ""
      flip = False
      if pos != -1:
        
        if d_child.__class__ == p:
          filler += d_child.PtoHTML()
        elif d_child.__class__ == lb:
          filler += d_child.LBtoHTML()
          #filler += " *LB CODE HERE* "
        elif d_child.__class__ == note:
          filler += d_child.NotetoHTML()
          #filler += " *NOTE CODE HERE* "
        elif d_child.__class__ == milestone:
          #filler += " *NEED TO CODE MILESTONE* " 	  
	  
	  #NEEDED FOR MANUSCRIPT B	  
          filler += d_child.MilestonetoHTML()
	  
        elif d_child.__class__ == add:
          #filler += " *NEED TO CODE ADD* "
          filler += d_child.AddtoHTML()
        elif d_child.__class__ == hi:
          #filler += " *NEED TO CODE HI* "
          filler += d_child.HitoHTML1()
        elif d_child.__class__ == expan:
          filler += d_child.ExpantoHTML()
          #filler += " *EPAN CODE HERE* "
        elif d_child.__class__ == dell: #might need to change this..... not sure
          #filler += " *NEED TO CODE DELL* "
	  filler += d_child.DelltoHTML()
        elif d_child.__class__ == damage:
          #filler += " *NEED TO CODE DAMAGE* "
	  filler += d_child.DamagetoHTML()
        elif d_child.__class__ == space:
          #filler += " *NEED TO CODE SPACE* "
	  filler += d_child.SpacetoHTML()
        else:
         pass
        if pos > 0: #text comes before placemarker
          end = temp[0:pos]
          temp = temp[pos+5:len(temp)]
          flip = True
        elif pos == 0: #text comes after placemarker
          if pos+5 > len(temp):
            end = ""
          else:
            temp2 = temp[5:len(temp)]
            #print "DEBUG(temp2): " + temp2
            next_pos = temp2.find('<-*->')
            if next_pos != -1:
              next_pos += 5
              end = temp[5:next_pos]
              temp = temp[next_pos:len(temp)]
            else:
              end = temp2
              pos = -1
              next_pos = len(temp)
          #temp = temp[next_pos:len(temp)]
        else:
          end = ""
          temp = temp[5:len(temp)]

        if flip == False:
          build_div2 += filler + end
        else:
          build_div2 += end + filler

      else:
           #print "DEBUG(end temp): " + temp
           build_div2 += temp
           #pass

    return build_div2 + '</span>'

#              #
#  CLASS NOTE  #
#              #
#              #
class note(XElement):
  def print1(self):
    #print enc(self.getText())[0]
    print self.getText()

  def printNote(self):
    expans = self.getChildren('expan')
    #we will use string slicing to enter the <expan> in the correct place
    if len(expans) > 0 and expans != None and expans != []:
      temp = self.getText()
      pos = temp.find('<-*->')
      index = 0
      extract = temp[index:pos]
      while pos != -1:
        #print pos
        #print "Character at position "+str(pos)+" is: "+ temp[pos]
        #extract = temp[index:pos-1]
        #       print extract + expans[0].getText()
        #print "DEBUG: "+temp
        if pos+5 >= len(temp):
          end = temp[pos+5:len(temp)-1]
          #print "DEBUG: END-> " + end
        elif temp[pos+5:len(temp)-1].find('<-*->') == -1:
          end = temp[pos+5:len(temp)]
          #print "DEBUG: END-> " + end

        else:
          end = temp[pos+5:temp[pos+5:len(temp)-1].find('<-*->')]
          #print "DEBUG: END-> " + end

        extract+=expans[0].getText()+end
        index = pos
        pos = temp[index+5:len(temp)-1].find('<-*->')

      print extract


    else:
     print self.getText()

  def procChildren(self):
    temp = self.getText()
    if False:
      print '<br/>DEBUG<br/>'
      print 'TEMP: '+temp+'<br/>'
      print '<br/>'

    children = self.getChildren()
    filler = ""
    end = ""
    real_end = "" #use if flip is set to true
    build_hi = ""
    if len(children) > 0:
      for h_child in children:
        pos = temp.find('<-*->')
        filler = ""
        real_end = ""
        flip = False
        if pos != -1:
          if h_child.__class__ == lb:
            filler += h_child.LBtoHTML()
            #filler += " *LB CODE HERE* "
          elif h_child.__class__ == note:
            filler += h_child.NotetoHTML()
            #filler += " *NOTE CODE HERE* "
          elif h_child.__class__ == milestone:
            #filler += " *NEED TO CODE MILESTONE* "
            filler += h_child.MilestonetoHTML()
          elif h_child.__class__ == add:
            #filler += " *NEED TO CODE ADD* "
            filler += h_child.AddtoHTML()
          elif h_child.__class__ == hi:
            #filler += " *NEED TO CODE HI* "
            filler += h_child.HitoHTML2()
          elif h_child.__class__ == expan:
            filler += h_child.ExpantoHTML()
            #filler += " *EPAN CODE HERE* "
          elif h_child.__class__ == dell: #might need to change this..... not sure
            #filler += " *NEED TO CODE DELL* "
            filler += h_child.DelltoHTML()
          elif h_child.__class__ == corr:
            filler += h_child.CorrtoHTML()
          elif h_child.__class__ == damage:
            #filler += " *NEED TO CODE DAMAGE* "
            filler += h_child.DamagetoHTML()
          elif h_child.__class__ == space:
            #filler += " *NEED TO CODE SPACE* "
            filler += h_child.SpacetoHTML()
	  elif h_child.__class__ == title:
	    filler += h_child.TitletoHTML()
          else:
            pass
          
          #if h_child.__class__ == lb:
          #  filler += h_child.LBtoHTML()
          #elif h_child.__class__ == hi:
          #  filler += h_child.HitoHTML2()

          #else:
          #  pass
          if pos > 0: #text comes before placemarker
            end = temp[0:pos]
            next_pos = temp[pos+5:len(temp)].find('<-*->')
            if next_pos == -1:
              real_end = temp[pos+5:len(temp)]
            else:
               next_pos += 5
               temp = temp[next_pos:len(temp)]

            flip = True

          elif pos == 0: #text comes after placemarker
            if pos+5 > len(temp):
              end = ""
            else:
              temp2 = temp[5:len(temp)]
              #print "DEBUG(temp2): " + temp2
              next_pos = temp2.find('<-*->')
              if next_pos != -1:
                next_pos += 5 #account for offset
                end = temp[5:next_pos]
                temp = temp[next_pos:len(temp)]
              else:
                end = temp2
                pos = -1
                next_pos = len(temp)

          #temp = temp[next_pos:len(temp)]
          else:
            end = ""
            temp = temp[5:len(temp)]

          if flip == False:
            build_hi += filler + end
          else:
            build_hi += end + filler + real_end

        else:
          #print "DEBUG(end temp): " + temp
          build_hi += temp
          #pass
    else:
      build_hi += temp

    return build_hi

  def remove_newline(self, text):
     pos = text.find('\n')
     if False:
       print '<br/>DEBUG<br/>'
       print 'pos: '+str(pos)+'<br/>'

     new_text = ""
     if pos != -1:
       if pos != 0:
          new_text += text[0:pos]
          new_text += " "
          new_text += self.remove_newline(text[pos+1:len(text)])
       else:
         new_text += " "
         new_text += self.remove_newline(text[1:len(text)])
     else:
       new_text += text
     if False:
       print '<br/>DEBUG<br/>'
       print 'Orig. Text: ' +text+'<br/>'
       print 'New_text: '+new_text+'<br/>'
       print '<br/>'


     return new_text

  def replace_double_quotes(self, text):
     pos = text.find('"')
     if False: # True: 
       print '<br/>DEBUG<br/>'
       print 'pos: '+str(pos)+'<br/>'
     new_text = ""
     if pos != -1:
       if pos != 0:        
          new_text += text[0:pos]
	  new_text += "\\'"
	  new_text += self.replace_double_quotes(text[pos+1:len(text)])	  
       else:
         new_text += "\\'"
         new_text += self.replace_double_quotes(text[1:len(text)])
     else:
       new_text += text
     if False:
       print '<br/>DEBUG<br/>'
       print 'Orig. Text: ' +text+'<br/>'
       print 'New_text: '+new_text+'<br/>'
       print '<br/>'			   
     return new_text
     
  def replace_single_quotes(self, text):
    pos = text.find("'")
    if False: # True:
    	print '<br/>DEBUG<br/>'
    	print 'pos: '+str(pos)+'<br/>'
    new_text = ""
    if pos != -1:
    	if pos != 0:
    		new_text += text[0:pos]
    		new_text += "\\'"
    		new_text += self.replace_double_quotes(text[pos+1:len(text)])
    	else:
    		new_text += "\\'"
    		new_text += self.replace_double_quotes(text[1:len(text)])
    else:
    	new_text += text
    if False:
    	print '<br/>DEBUG<br/>'
    	print 'Orig. Text: ' +text+'<br/>'
    	print 'New_text: '+new_text+'<br/>'
    	print '<br/>'
    return new_text

  def replace_aelig(self, text):
     #pos = text.find('ï¿½')
     pos = text.find('æ')
     if False: # True:
       print '<br/>DEBUG<br/>'
       print 'pos: '+str(pos)+'<br/>'
     new_text = ""
     if pos != -1:
       if pos != 0:
          new_text += text[0:pos]
          new_text += "&aelig;" #replace aelig
          new_text += self.replace_double_quotes(text[pos+1:len(text)])
       else:
         new_text += "&aelig;"
         new_text += self.replace_double_quotes(text[1:len(text)])
     else:
       new_text += text
     if False: 
       print '<br/>DEBUG<br/>'
       print 'Orig. Text: ' +text+'<br/>'
       print 'New_text: '+new_text+'<br/>'
       print '<br/>'                      
     return new_text
   
       
  def NotetoHTML(self):
    DEBUG = False
    children = self.getChildren()  
    build_note = '<span style="position: relative;" '
    mouse_over_code = 'onmouseover="this.T_FONTSIZE=\'12px\'; this.T_SHADOWWIDTH=5; this.T_SHADOWCOLOR=\'#553355\'; this.T_TITLE='+"'Note'"+';return escape(\''
    text = self.procChildren()
    #new_text = self.replace_single_quotes(text)
    new_text = text.replace("'", "\\'")
    #print 'SINGLEQUOTES:', new_text
    #new_text = self.replace_double_quotes(new_text)
    new_text = new_text.replace("\"", "&quot;")
    #new_text = self.replace_aelig(new_text)
    new_text = new_text.replace("æ", "&aelig;")    
    #mouse_over_code += self.remove_newline(new_text)
    #print 'NEW_TEXT:', new_text
    mouse_over_code += new_text.replace("\n", " ")
    mouse_over_code += '\');"><img src="pics/note.jpg"/></span>'
    #print 'MOUSEOVERCODE:', mouse_over_code
    #mouse_over_code = 'onmouseover="return escape(\'Some text\')" ><img src="pics/note.jpg"/></span>'
    build_note += mouse_over_code
    debug_info = ""
    if DEBUG:
      debug_info = '<br/><br/>DEBUG<br/>'
      debug_info += 'New_text: '+new_text+'<br/>'
      debug_info += 'mouse_over_code: ' + mouse_over_code +'<br/>'
      debug_info += '<br/>'
    #return '<span>NOTE</span>'
    return build_note + debug_info
    
  def NotetoHTML2(self):
    expans = self.getChildren()
    #lb = self.getChildren('lb')
    #if len(lb) > 0:
     # return "**********FOUND LB"

    #for x in expans:
    #  t = x.__class__
    #  print t
    #  if x.__class__ == expan:
    #    print "TITLE"
    #return "******"
    #we will use string slicing to enter the <expan> in the correct place
    if len(expans) > 0:
      temp = self.getText()
      pos = temp.find('<-*->')
      index = 0
      #setup the note html here
      extract = '<span class="note" style="width: 45px;" height="100px"><span><img src="pics/note.jpg"/><span><table><tr><td>'+temp[index:pos]
      #extract = '<span class="note" style="width: 45px;" id="note" height="100px"><span style="color: blue; font: sans-serif; font-size: 12px;">(NOTE)<spa><table><tr><td><div>'+temp[index:pos]

      for x in expans:
          #extract = '<div style="width: 45px;" id="note" height="100px"><div style="color: blue; font: sans-serif; font-size: 12px;">(NOTE)<table border=""><tr><td>'+temp[index:pos]
          #close_extract =
       #print "DEBUG: "+temp
        #pos = temp.find('<-*->')
        while pos != -1:
          #print pos
          #print "Character at position "+str(pos)+" is: "+ temp[pos]
          #extract = temp[index:pos-1]
          #       print extract +"<ital>" +expans[0].getText()+"</ital>"
          #print "DEBUG: "+temp
          if pos+5 >= len(temp):
            end = temp[pos+5:len(temp)-1]
          elif temp[pos+5:len(temp)-1].find('<-*->') == -1:
            end = temp[pos+5:len(temp)-1]
          else:
            end = temp[pos+5:temp[pos+5:len(temp)-1].find('<-*->')]
          if x.__class__ == expan:
            #print "*****************EXPAN FOUND*****************\n"
            extract+= x.ExpantoHTML()#'<span style="font-style: italic;">' +x.getText()+"</span>"+end
          #not sure what to do with title yet...
          elif x.__class__ == title:
            #print "*****************TITLE FOUND*****************\n"
            pad = '<![CDATA[&nbsp;]]>'
            if x.getText()[0] == '.' or x.getText()[0] == ',' or x.getText()[0] == ':' or x.getText()[0] == ';' or x.getText()[0] =='(' or x.getText()[0] == '\'' or x.getText()[0] =='"' or x.getText()[0] =='!' or x.getText()[0] =="?":
               pad = ''

            extract +='<span style="font-weight: bold;">'+pad+x.getText()+'</span>'+end

          index = pos
          pos = temp[index+5:len(temp)-1].find('<-*->')

      return extract + '</td></tr></table></span></span></span>'
    else:
      return '<span style="width: 45px;" class="note" height="100px"><span><img src="pics/note.jpg"/><span><table><tr><td>'+self.getText()+ '</td></tr></table></span></span></span>'

      #print "extracted string was: " +extract
      #print temp +"<ex>"+ expans[0].getText()+'</ex>'
      #temp = temp[pos-4:pos-2]
      #print temp


class expan(XElement):
  def ExpantoHTML(self):
    #return '<h12 style="font-style: italic; position: relative;">' +self.getText()+'</h12>'
    return '<span style="font-style: italic;">'+self.getText()+'</span>'

class add(XElement):
  def AddtoHTML_no_margin(self):
    attrs = self.getAttributes()
    place = attrs.getFirst('place')
    add_children = self.getChildren()
    temp_text = ""
    if len(add_children) > 0:
       temp = self.getText()
       filler = ""
       end = ""
       #begin = ""
       for add_child in add_children:
         pos = temp.find('<-*->')
         #print "DEBUG: "+temp
         filler = ""
         flip = False
         if pos != -1:
           if add_child.__class__ == lb:
             filler += add_child.LBtoHTML()
             #filler += " *LB CODE HERE* "
           elif add_child.__class__ == note:
             filler += add_child.NotetoHTML()
             #filler += " *NOTE CODE HERE* "
           elif add_child.__class__ == milestone:
             #filler += " *NEED TO CODE MILESTONE* "
             filler += add_child.MilestonetoHTML()
           elif add_child.__class__ == add:
             #filler += " *NEED TO CODE ADD* "
             filler += add_child.AddtoHTML()
           elif add_child.__class__ == hi:
             #filler += " *NEED TO CODE HI* "
             filler += add_child.HitoHTML1()
           elif add_child.__class__ == expan:
             filler += add_child.ExpantoHTML()
             #filler += " *EPAN CODE HERE* "
           elif add_child.__class__ == dell: #might need to change this..... not sure
             #filler += " *NEED TO CODE DELL* "
             filler += add_child.DelltoHTML()
           elif add_child.__class__ == damage:
             #filler += " *NEED TO CODE DAMAGE* "
             filler += add_child.DamagetoHTML()
           elif add_child.__class__ == space:
             #filler += " *NEED TO CODE SPACE* "
             filler += add_child.SpacetoHTML()
           else:
             pass
           if pos > 0:
             end = temp[0:pos]
             temp = temp[pos+5:len(temp)]
             flip = True
           elif pos == 0:
             if pos+5 > len(temp):
               end = ""
             else:
               temp2 = temp[5:len(temp)]
               next_pos = temp2.find('<-*->') + 5
               end = temp[5:next_pos]
             temp = temp[next_pos:len(temp)]
           else:
             end = ""
             temp = temp[5:len(temp)]
           if flip == False:
             temp_text += filler + end
           else:
             temp_text += end + filler  
      #return " *ADD w/ Children code here* "
    else:
      temp_text = self.getText()
    if place == 'marginRight':
      #return '<div><span id="marginRight">'+temp_text+'</span></div>'
       return ""
    elif place == 'interlinear':
      return '<span class="interlinear">'+temp_text+'</span>'
    elif place == 'marginLeft':
      #return '<span id="marginLeft">'+temp_text+'</span>'
      return ""
    elif place == 'center':
      #return '<center><span id="center">'+temp_text+'</span></center>'
      return ""
    else:
      return '<span class="add">'+temp_text+'</span>'

  def AddtoHTML(self):
    attrs = self.getAttributes()
    place = attrs.getFirst('place')
    add_children = self.getChildren()
    temp_text = ""
    if len(add_children) > 0:
       temp = self.getText()
       filler = ""
       end = ""
       #begin = ""
       for add_child in add_children:
         pos = temp.find('<-*->')
         #print "DEBUG: "+temp
         filler = ""
         flip = False
         if pos != -1:
           if add_child.__class__ == lb:
             filler += add_child.LBtoHTML()
             #filler += " *LB CODE HERE* "
           elif add_child.__class__ == gloss:
	         filler += add_child.glosstoHTML()
	   elif add_child.__class__ == note:
             filler += add_child.NotetoHTML()
             #filler += " *NOTE CODE HERE* "
           elif add_child.__class__ == milestone:
             #filler += " *NEED TO CODE MILESTONE* "
             filler += add_child.MilestonetoHTML()
           elif add_child.__class__ == add:
             #filler += " *NEED TO CODE ADD* "
             filler += add_child.AddtoHTML()
           elif add_child.__class__ == hi:
             #filler += " *NEED TO CODE HI* "
	         filler += add_child.HitoHTML1()
           elif add_child.__class__ == expan:
             filler += add_child.ExpantoHTML()
             #filler += " *EPAN CODE HERE* "
           elif add_child.__class__ == dell: #might need to change this..... not sure
             #filler += " *NEED TO CODE DELL* "
	         filler += add_child.DelltoHTML()
           elif add_child.__class__ == damage:
             #filler += " *NEED TO CODE DAMAGE* "
	         filler += add_child.DamagetoHTML()
           elif add_child.__class__ == space:
             #filler += " *NEED TO CODE SPACE* "
	         filler += add_child.SpacetoHTML()
           else:
             pass
            
           if pos > 0:
             end = temp[0:pos]
             temp = temp[pos+5:len(temp)]
             flip = True
           elif pos == 0:
             if pos+5 > len(temp):
               end = ""
             else:
               temp2 = temp[5:len(temp)]
               next_pos = temp2.find('<-*->') + 5
               end = temp[5:next_pos]
             temp = temp[next_pos:len(temp)]
           else:
             end = ""
             temp = temp[5:len(temp)]
           if flip == False:
             temp_text += filler + end
           else:
             temp_text += end + filler
           
       # This appears to fix a problem where anything after a nested element was removed. -cg    
       if len(temp) > 1:
       	   temp_text += temp

      #return " *ADD w/ Children code here* "
    else:
      temp_text = self.getText()
    
    if place == 'marginRight':
      return '<span class="marginRight">'+temp_text+'</span>'
    elif place == 'interlinear':
      return '<span class="interlinear">'+temp_text+'</span>'
    elif place == 'marginLeft':
      return '<span class="marginLeft">'+temp_text+'</span>'
    elif place == 'center':
      return '<center><span class="center">'+temp_text+'</span></center>'
    else:
      return '<span class="add">'+temp_text+'</span>'

class lb(XElement):
  def getLB(self):
    return '\n'
  def LBtoHTML_paged(self):
    global CURRENT_FILE
    CURRENT_FILE.add_text("<br/>")
  def LBtoHTML(self):
    return "<br/>"

class dell(XElement): #note predifined python function use causion when calling either of them
  def DelltoHTML(self):
    attrs = self.getAttributes()
    erasure = attrs.getFirst('erasure')
    status = attrs.getFirst('status')
    return '<span class="del">'+self.getText()+'</span>'

class space(XElement):
  def SpacetoHTML(self):
    attrs = self.getAttributes()
    dim = attrs.getFirst('dim')
    _space =""
    if dim == "horizontal" or dim == None:
      #_space = '<![CDATA[&nbsp;]]>'
      _space = '&nbsp;'
    elif dim != None:
      _space = '<br/>'
    build_space =""
    extent = attrs.getFirst('extent')
    if dim == None:
      dim = "horizontal"
      extent = 1
    if dim != None and dim != "" and dim != "None":
      try:
        i = 0
        while i < int(extent):
          i+=1
          build_space += _space
      except:
        build_space += " *ERROR in SPACE CALCULATION* "
    else:
      print str(dim)
      print "ERROR: Unrecognized space calculation..."

    return build_space
class damage(XElement):
  def remove_newline(self, text):
     pos = text.find('\n')
     if False:
       print '<br/>DEBUG<br/>'
       print 'pos: '+str(pos)+'<br/>'
     new_text = ""
     if pos != -1:
       if pos != 0:
          new_text += text[0:pos]
          new_text += " "
          new_text += self.remove_newline(text[pos+1:len(text)])
       else:
         new_text += " "
         new_text += self.remove_newline(text[1:len(text)])
     else:
       new_text += text
     if False:
       print '<br/>DEBUG<br/>'
       print 'Orig. Text: ' +text+'<br/>'
       print 'New_text: '+new_text+'<br/>'
       print '<br/>'
     return new_text

  def replace_double_quotes(self, text):
     pos = text.find('"')
     if False: # True:
       print '<br/>DEBUG<br/>'
       print 'pos: '+str(pos)+'<br/>'
     new_text = ""
     if pos != -1:
       if pos != 0:
          new_text += text[0:pos]
          new_text += "\\'"
          new_text += self.replace_double_quotes(text[pos+1:len(text)])
       else:
         new_text += "\\'"
         new_text += self.replace_double_quotes(text[1:len(text)])
     else:
       new_text += text
     if False:
       print '<br/>DEBUG<br/>'
       print 'Orig. Text: ' +text+'<br/>'
       print 'New_text: '+new_text+'<br/>'
       print '<br/>'
     return new_text
     
  def DamagetoHTML_no_popup(self):
    attrs = self.getAttributes()
    _type = attrs.getFirst('type')
    extent = attrs.getFirst('extent')
    if extent == None:
      extent = 'N/A'
    #print "<br/>DEBUG<br/>"
    #print "Type: "+str(_type)+"<br/>"
    #print "Extent: "+str(extent)+"<br/>"
    text = '<div>Type of damage: '+_type+'<br/>Extent of damage: '+extent+' characters</div>'
    new_text = self.replace_double_quotes(text)
    text =  self.remove_newline(new_text)
    #return '<span id="damage">'+self.getText()+'</span>'
    return '<span class="damage">'+self.getText()+'</span>'

  def DamagetoHTML(self):
    attrs = self.getAttributes()
    _type = attrs.getFirst('type')
    extent = attrs.getFirst('extent')
    if extent == None:
      extent = 'N/A'
    #print "<br/>DEBUG<br/>"
    #print "Type: "+str(_type)+"<br/>"
    #print "Extent: "+str(extent)+"<br/>"
    if extent != 'N/A':
      text = '<div>Type of damage: '+_type+'<br/>Extent of damage: '+extent+' characters</div>'
    else:
      text = '<div>Type of damage: '+_type+'<br/>Extent of damage: '+extent+'</div>'
    new_text = self.replace_double_quotes(text)
    text =  self.remove_newline(new_text)
    #return '<span id="damage">'+self.getText()+'</span>'
    #return '<span class="damage" onmouseover="this.T_SHADOWCOLOR=\'#553355\'; this.T_TITLE='+"'Damage'"+'; return escape('+"'"+text+"'"+')">'+self.getText()+'</span>'

    temp = self.getText()
    DEBUG = False #True
    if DEBUG:
      print '<br/>DEBUG<br/>'
      print 'TEMP: '+temp+'<br/>'      
      print '<br/>'

    children = self.getChildren()
    filler = ""
    end = ""
    real_end = "" #use if flip is set to true
    build_hi = '<span class="damage" onmouseover="this.T_FONTSIZE=\'12px\';this.T_SHADOWCOLOR=\'#553355\'; this.T_TITLE='+"'Damage'"+'; return escape('+"'"+text+"'"+')">'
    if len(children) > 0:
      for h_child in children:
        pos = temp.find('<-*->')
        filler = ""
	real_end = ""
        flip = False
        if pos != -1:
          if h_child.__class__ == lb:
	    filler += h_child.LBtoHTML()
	    #filler += " *LB CODE HERE* "
	  elif h_child.__class__ == note:
	    filler += h_child.NotetoHTML()
	    #filler += " *NOTE CODE HERE* "
	  elif h_child.__class__ == milestone:
	    #filler += " *NEED TO CODE MILESTONE* "
	    filler += h_child.MilestonetoHTML()
	  elif h_child.__class__ == add:
	    #filler += " *CODE ADD* "
	    filler += h_child.AddtoHTML()
	  elif h_child.__class__ == hi:
	    #there seems there may be a problem with the hi rendering on large manuscripts...here is where u disable that by commenting it out and adding the "Need to code hi" instead
	    #filler += " *NEED TO CODE HI* "
	    filler += h_child.HitoHTML2()
	  elif h_child.__class__ == expan:
	    filler += h_child.ExpantoHTML()
	    #filler += " *EPAN CODE HERE* "
	  elif h_child.__class__ == dell: #might need to change this..... not sure
	    #filler += " *NEED TO CODE DELL* "
	    filler += h_child.DelltoHTML()
	  elif h_child.__class__ == corr:
	    filler += h_child.CorrtoHTML()
	  elif h_child.__class__ == damage:
	    #filler += " *NEED TO CODE DAMAGE* "
	    filler += h_child.DamagetoHTML()
	  elif h_child.__class__ == space:
	    #filler += " *NEED TO CODE SPACE* "
	    filler += h_child.SpacetoHTML()
	  else:
	    pass
	    
          #if h_child.__class__ == lb:
          #  filler += h_child.LBtoHTML()
          #elif h_child.__class__ == hi:
          #  filler += h_child.HitoHTML2()
	    
          #else:
          #  pass
          if pos > 0: #text comes before placemarker
            end = temp[0:pos]
            temp = temp[pos+5:len(temp)]
	    next_pos = temp.find('<-*->')
	    if next_pos == -1:
              real_end = temp
	    #else:
	    #   next_pos += 5
	    #   temp = temp[next_pos:len(temp)]
	       
            flip = True
	    
          elif pos == 0: #text comes after placemarker
            if pos+5 > len(temp):
              #print "<br/>TEMP -2: "+ temp +"<br/>"
              end = ""
            else:
              temp2 = temp[5:len(temp)]
              #print "<br/>DEBUG(temp2): " + temp2 +"<br/>"
              next_pos = temp2.find('<-*->')
              if next_pos != -1:
                next_pos += 5 #account for offset
                end = temp[5:next_pos]
                temp = temp[next_pos:len(temp)]
              else:
                end = temp2
                #pos = -1
                #next_pos = len(temp)

          #temp = temp[next_pos:len(temp)]
          else:
            end = ""
            temp = temp[5:len(temp)]

          if flip == False:
            build_hi += filler + end
          else:
            build_hi += end + filler + real_end

        else:
          #print "DEBUG(end temp): " + temp
          build_hi += temp
          #pass
    else:
      build_hi += temp
      temp =""
    if DEBUG:
      print "<br/>DEBUG<br/>"
      print "build_hi: " + build_hi
      print "<br/>"
    #if len(temp) != 0:
    #  build_hi += temp
    return build_hi + '</span>'
    
  def DamagetoHTML2(self):
    attrs = self.getAttributes()
    _type = attrs.getFirst('type')
    extent = attrs.getFirst('extent')
    if extent == None:
      extent = 'N/A'
    #print "<br/>DEBUG<br/>"
    #print "Type: "+str(_type)+"<br/>"
    #print "Extent: "+str(extent)+"<br/>"
    if extent != 'N/A':
      text = '<div>Type of damage: '+_type+'<br/>Extent of damage: '+extent+' characters</div>'
    else:
      text = '<div>Type of damage: '+_type+'<br/>Extent of damage: '+extent+'</div>'
    new_text = self.replace_double_quotes(text)
    text =  self.remove_newline(new_text)
    #return '<span id="damage">'+self.getText()+'</span>'
    return '<span class="damage" onmouseover="this.T_SHADOWCOLOR=\'#553355\'; this.T_TITLE='+"'Damage'"+'; return escape('+"'"+text+"'"+')">'+self.getText()+'</span>'

class corr(XElement):
  def CorrtoHTML(self):
   build_corr = '<span class="corr">'
   for c_child in self.getChildren():
     if c_child.__class__ == add:
       build_corr += c_child.AddtoHTML()
   build_corr += '</span>'  

   return build_corr

class gloss(XElement):
  #def glosstoHTML( self ):
    #return self.getText()

  def glosstoHTML(self):
    temp = self.getText()
    DEBUG = False #True
    if DEBUG:
      print '<br/>DEBUG<br/>'
      print 'TEMP: '+temp+'<br/>'      
      print '<br/>'

    children = self.getChildren()
    filler = ""
    end = ""
    real_end = "" #use if flip is set to true
    build_hi = ""
    if len(children) > 0:
      for h_child in children:
        pos = temp.find('<-*->')
        filler = ""
	real_end = ""
        flip = False
        if pos != -1:
          if h_child.__class__ == lb:
	    filler += h_child.LBtoHTML()
	    #filler += " *LB CODE HERE* "
	  elif h_child.__class__ == note:
	    filler += h_child.NotetoHTML()
	    #filler += " *NOTE CODE HERE* "
	  elif h_child.__class__ == milestone:
	    #filler += " *NEED TO CODE MILESTONE* "
	    filler += h_child.MilestonetoHTML()
	  elif h_child.__class__ == add:
	    #filler += " *NEED TO CODE ADD* "
	    filler += h_child.AddtoHTML()
	  elif h_child.__class__ == hi:
	    #filler += " *NEED TO CODE HI* "
	    filler += h_child.HitoHTML2()
	  elif h_child.__class__ == expan:
	    filler += h_child.ExpantoHTML()
	    #filler += " *EPAN CODE HERE* "
	  elif h_child.__class__ == dell: #might need to change this..... not sure
	    #filler += " *NEED TO CODE DELL* "
	    filler += h_child.DelltoHTML()
	  elif h_child.__class__ == corr:
	    filler += h_child.CorrtoHTML()
	  elif h_child.__class__ == damage:
	    #filler += " *NEED TO CODE DAMAGE* "
	    filler += h_child.DamagetoHTML()
	  elif h_child.__class__ == space:
	    #filler += " *NEED TO CODE SPACE* "
	    filler += h_child.SpacetoHTML()
	  else:
	    pass
	    
          #if h_child.__class__ == lb:
          #  filler += h_child.LBtoHTML()
          #elif h_child.__class__ == hi:
          #  filler += h_child.HitoHTML2()
	    
          #else:
          #  pass
          if pos > 0: #text comes before placemarker
            end = temp[0:pos]
            temp = temp[pos+5:len(temp)]
	    next_pos = temp.find('<-*->')
	    if next_pos == -1:
              real_end = temp
	    #else:
	    #   next_pos += 5
	    #   temp = temp[next_pos:len(temp)]
	       
            flip = True
	    
          elif pos == 0: #text comes after placemarker
            if pos+5 > len(temp):
              #print "<br/>TEMP -2: "+ temp +"<br/>"
              end = ""
            else:
              temp2 = temp[5:len(temp)]
              #print "<br/>DEBUG(temp2): " + temp2 +"<br/>"
              next_pos = temp2.find('<-*->')
              if next_pos != -1:
                next_pos += 5 #account for offset
                end = temp[5:next_pos]
                temp = temp[next_pos:len(temp)]
              else:
                end = temp2
                #pos = -1
                #next_pos = len(temp)

          #temp = temp[next_pos:len(temp)]
          else:
            end = ""
            temp = temp[5:len(temp)]

          if flip == False:
            build_hi += filler + end
          else:
            build_hi += end + filler + real_end

        else:
          #print "DEBUG(end temp): " + temp
          build_hi += temp
          #pass
    else:
      build_hi += temp
      temp =""
    if DEBUG:
      print "<br/>DEBUG<br/>"
      print "build_hi: " + build_hi
      print "<br/>"
    #if len(temp) != 0:
    #  build_hi += temp
    return build_hi

class handShift(XElement):
  def printHandshift(self):
    print "Not yet"

class MANUSCRIPT:  #this class holds base manuscript functions
  def get_line_version(self, line_number):
    build_line = "<div>"
    texts = self.manuscript.getChildren("text")
    bodys = texts[0].getChildren('body')
    div1s = bodys[0].getChildren('div1')	    
    #div1s = self.manuscript.getChildren("text")[0].getChildren('body')[0].getChildren('div1')
    for d_child in div1s:
      for div2_child in d_child.getChildren('div2'):
        temp_line_number = div2_child.getLineNumberOnly()
	if temp_line_number[1:len(temp_line_number)] == line_number[1:len(line_number)]:
	  build_line += div2_child.Div2toHTML(None, False)
	  #for p_child in div2_child.getChildren('p'):
	  #  build_line += p_child.get_p_version()    
    build_line += "</div>"
    return build_line
    
    
  def get_page_for_line(self, line_number):
    print "working on it!"
  def get_line(self, line_number):
    build_line=""
    #build_line += line_number[1
    texts = self.manuscript.getChildren("text")
    bodys = texts[0].getChildren('body')
    div1s = bodys[0].getChildren('div1')
    for d_child in div1s:
      for div2_child in d_child.getChildren('div2'):
        temp_line_number = div2_child.getLineNumberOnly()
        if temp_line_number[1:len(temp_line_number)] == line_number[1:len(line_number)]:
          #build_line += "DEBUG: "+ temp_line_number
          for p_child in div2_child.getChildren('p'):
            build_line += p_child.get_p_text()

    return build_line

  def has_line(self, line_number): #the line number passed in is already stripped of the leading character
    exists = False #assume line doesn't exist
    texts = self.manuscript.getChildren("text")
    bodys = texts[0].getChildren('body')
    div1s = bodys[0].getChildren('div1')
    for d_child in div1s:
      for div2_child in d_child.getChildren('div2'):
        temp_line_number = div2_child.getLineNumberOnly()
        if temp_line_number[1:len(temp_line_number)] == line_number:
          exists = True #line exists

    return exists
class TSBOC121MS(MANUSCRIPT):
  def __init__(self, path):
    self.my_classes = { 'TEI.2':TEI2, 'teiHeader':teiHeader, 'fileDesc':fileDesc, 'titleStmt':titleStmt, 'publicationStmt':publicationStmt, 
               'title':title, 'editor':editor, 'respStmt':respStmt, 'resp':resp, 'name':name, 'hi':hi, 'publisher':publisher, 
	       'pubPlace':pubPlace, 'idno':idno, 'availability':availability, 'p':p, 'date':date, 'sourceDesc':sourceDesc, 
	       'biblFull':biblFull, 'editionStmt':editionStmt, 'extent':extent, 'seriesStmt':seriesStmt, 'encodingDesc':encodingDesc, 
	       'editorialDecl':editorialDecl, 'list':list, 'head':head, 'item':item, 'label':label, 'term':term, 'profileDesc':profileDesc, 
	       'langUsage':langUsage, 'language':language, 'handList':handList, 'hand':hand, 'revisionDesc':revisionDesc, 'change':change, 
	       'text':text, 'body':body, 'div1':div1, 'xref':xref, 'milestone':milestone, 'div2':div2, 'note':note, 'expan':expan, 
	       'add':add, 'lb':lb, 'del':dell, 'space':space, 'damage':damage, 'corr':corr, 'gloss':gloss, 'handShift':handShift }
    self.xparser = XElementParser(self.my_classes)
    #self.manuscript = self.xparser.process('data/TOEP482.xml')
    self.manuscript = self.xparser.process(path)
    #del self.xparser
 
class JUNIUSMS(MANUSCRIPT):
  def __init__(self, path):
    self.my_classes = { 'TEI.2':TEI2, 'teiHeader':teiHeader, 'fileDesc':fileDesc, 'titleStmt':titleStmt, 'publicationStmt':publicationStmt, 
               'title':title, 'editor':editor, 'respStmt':respStmt, 'resp':resp, 'name':name, 'hi':hi, 'publisher':publisher, 
	       'pubPlace':pubPlace, 'idno':idno, 'availability':availability, 'p':p, 'date':date, 'sourceDesc':sourceDesc, 
	       'biblFull':biblFull, 'editionStmt':editionStmt, 'extent':extent, 'seriesStmt':seriesStmt, 'encodingDesc':encodingDesc, 
	       'editorialDecl':editorialDecl, 'list':list, 'head':head, 'item':item, 'label':label, 'term':term, 'profileDesc':profileDesc, 
	       'langUsage':langUsage, 'language':language, 'handList':handList, 'hand':hand, 'revisionDesc':revisionDesc, 'change':change, 
	       'text':text, 'body':body, 'div1':div1, 'xref':xref, 'milestone':milestone, 'div2':div2, 'note':note, 'expan':expan, 
	       'add':add, 'lb':lb, 'del':dell, 'space':space, 'damage':damage, 'corr':corr, 'gloss':gloss, 'handShift':handShift, 
	       'column':column, 'col_left':col_left, 'col_right':col_right }
    self.xparser = XElementParser(self.my_classes)
    #self.manuscript = self.xparser.process('data/TOEP482.xml')
    self.manuscript = self.xparser.process(path)
    #del self.xparser

class TOEP482MS(MANUSCRIPT):
  def __init__(self, path):
    self.my_classes = { 'TEI.2':TEI2, 'teiHeader':teiHeader, 'fileDesc':fileDesc, 'titleStmt':titleStmt, 'publicationStmt':publicationStmt, 
               'title':title, 'editor':editor, 'respStmt':respStmt, 'resp':resp, 'name':name, 'hi':hi, 'publisher':publisher, 
	       'pubPlace':pubPlace, 'idno':idno, 'availability':availability, 'p':p, 'date':date, 'sourceDesc':sourceDesc, 
	       'biblFull':biblFull, 'editionStmt':editionStmt, 'extent':extent, 'seriesStmt':seriesStmt, 'encodingDesc':encodingDesc, 
	       'editorialDecl':editorialDecl, 'list':list, 'head':head, 'item':item, 'label':label, 'term':term, 'profileDesc':profileDesc, 
	       'langUsage':langUsage, 'language':language, 'handList':handList, 'hand':hand, 'revisionDesc':revisionDesc, 'change':change, 
	       'text':text, 'body':body, 'div1':div1, 'xref':xref, 'milestone':milestone, 'div2':div2, 'note':note, 'expan':expan, 
	       'add':add, 'lb':lb, 'del':dell, 'space':space, 'damage':damage, 'corr':corr, 'gloss':gloss, 'handShift':handShift }
    self.xparser = XElementParser(self.my_classes)
    #self.manuscript = self.xparser.process('data/TOEP482.xml')
    self.manuscript = self.xparser.process(path)
    #del self.xparser
													     
class LAUD482MS(MANUSCRIPT):
  def __init__(self, path):
    self.my_classes = { 'TEI.2':TEI2, 'teiHeader':teiHeader, 'fileDesc':fileDesc, 'titleStmt':titleStmt, 'publicationStmt':publicationStmt, 
             'title':title, 'editor':editor, 'respStmt':respStmt, 'resp':resp, 'name':name, 'hi':hi, 'publisher':publisher, 
	     'pubPlace':pubPlace, 'idno':idno, 'availability':availability, 'p':p, 'date':date, 'sourceDesc':sourceDesc, 
	     'biblFull':biblFull, 'editionStmt':editionStmt, 'extent':extent, 'seriesStmt':seriesStmt, 'encodingDesc':encodingDesc, 
	     'editorialDecl':editorialDecl, 'list':list, 'head':head, 'item':item, 'label':label, 'term':term, 'profileDesc':profileDesc, 
	     'langUsage':langUsage, 'language':language, 'handList':handList, 'hand':hand, 'revisionDesc':revisionDesc, 'change':change, 
	     'text':text, 'body':body, 'div1':div1, 'xref':xref, 'milestone':milestone, 'div2':div2, 'note':note, 'expan':expan, 
	     'add':add, 'lb':lb, 'del':dell, 'space':space, 'damage':damage, 'corr':corr, 'gloss':gloss, 'handShift':handShift }
	     
    self.xparser = XElementParser(self.my_classes)
    #self.manuscript = self.xparser.process('data/LAUD482.xml')
    self.manuscript = self.xparser.process(path)
    #del self.xparser
															   
class TCTH8558MS(MANUSCRIPT):
  def __init__(self, path):
    self.my_classes = { 'TEI.2':TEI2, 'teiHeader':teiHeader, 'fileDesc':fileDesc, 'titleStmt':titleStmt, 'publicationStmt':publicationStmt, 
               'title':title, 'editor':editor, 'respStmt':respStmt, 'resp':resp, 'name':name, 'hi':hi, 'publisher':publisher, 
               'pubPlace':pubPlace, 'idno':idno, 'availability':availability, 'p':p, 'date':date, 'sourceDesc':sourceDesc, 
               'biblFull':biblFull, 'editionStmt':editionStmt, 'extent':extent, 'seriesStmt':seriesStmt, 'encodingDesc':encodingDesc, 
               'editorialDecl':editorialDecl, 'list':list, 'head':head, 'item':item, 'label':label, 'term':term, 'profileDesc':profileDesc, 
               'langUsage':langUsage, 'language':language, 'handList':handList, 'hand':hand, 'revisionDesc':revisionDesc, 'change':change, 
               'text':text, 'body':body, 'div1':div1, 'xref':xref, 'milestone':milestone, 'div2':div2, 'note':note, 'expan':expan, 
               'add':add, 'lb':lb, 'del':dell, 'space':space, 'damage':damage, 'corr':corr, 'gloss':gloss, 'handShift':handShift }

    self.xparser = XElementParser(self.my_classes)
    #self.manuscript = self.xparser.process('data/TCTH8558.xml')
    self.manuscript = self.xparser.process(path)
    #del self.xparser

class BX8558MS(MANUSCRIPT):
  def __init__(self, path):
    self.my_classes = { 'TEI.2':TEI2, 'teiHeader':teiHeader, 'fileDesc':fileDesc, 'titleStmt':titleStmt, 'publicationStmt':publicationStmt, 
               'title':title, 'editor':editor, 'respStmt':respStmt, 'resp':resp, 'name':name, 'hi':hi, 'publisher':publisher, 
               'pubPlace':pubPlace, 'idno':idno, 'availability':availability, 'p':p, 'date':date, 'sourceDesc':sourceDesc, 
               'biblFull':biblFull, 'editionStmt':editionStmt, 'extent':extent, 'seriesStmt':seriesStmt, 'encodingDesc':encodingDesc, 
               'editorialDecl':editorialDecl, 'list':list, 'head':head, 'item':item, 'label':label, 'term':term, 'profileDesc':profileDesc, 
               'langUsage':langUsage, 'language':language, 'handList':handList, 'hand':hand, 'revisionDesc':revisionDesc, 'change':change, 
               'text':text, 'body':body, 'div1':div1, 'xref':xref, 'milestone':milestone, 'div2':div2, 'note':note, 'expan':expan, 
               'add':add, 'lb':lb, 'del':dell, 'space':space, 'damage':damage, 'corr':corr, 'gloss':gloss, 'handShift':handShift }

    self.xparser = XElementParser(self.my_classes)
    #self.manuscript = self.xparser.process('data/BX8558.xml')
    self.manuscript = self.xparser.process(path)
    #del self.xparser

class TOEI190MS(MANUSCRIPT):
  def __init__(self, path):
    self.my_classes = { 'TEI.2':TEI2, 'teiHeader':teiHeader, 'fileDesc':fileDesc, 'titleStmt':titleStmt, 'publicationStmt':publicationStmt, 
               'title':title, 'editor':editor, 'respStmt':respStmt, 'resp':resp, 'name':name, 'hi':hi, 'publisher':publisher, 
               'pubPlace':pubPlace, 'idno':idno, 'availability':availability, 'p':p, 'date':date, 'sourceDesc':sourceDesc, 
               'biblFull':biblFull, 'editionStmt':editionStmt, 'extent':extent, 'seriesStmt':seriesStmt, 'encodingDesc':encodingDesc, 
               'editorialDecl':editorialDecl, 'list':list, 'head':head, 'item':item, 'label':label, 'term':term, 'profileDesc':profileDesc, 
               'langUsage':langUsage, 'language':language, 'handList':handList, 'hand':hand, 'revisionDesc':revisionDesc, 'change':change, 
               'text':text, 'body':body, 'div1':div1, 'xref':xref, 'milestone':milestone, 'div2':div2, 'note':note, 'expan':expan, 
               'add':add, 'lb':lb, 'del':dell, 'space':space, 'damage':damage, 'corr':corr, 'gloss':gloss, 'handShift':handShift }

    self.xparser = XElementParser(self.my_classes)
    #self.manuscript = self.xparser.process('data/TOEI190.xml')
    self.manuscript = self.xparser.process(path)
    #del self.xparser

class CORP190MS(MANUSCRIPT):
  def __init__(self, path):
    self.my_classes = { 'TEI.2':TEI2, 'teiHeader':teiHeader, 'fileDesc':fileDesc, 'titleStmt':titleStmt, 'publicationStmt':publicationStmt, 
               'title':title, 'editor':editor, 'respStmt':respStmt, 'resp':resp, 'name':name, 'hi':hi, 'publisher':publisher, 
               'pubPlace':pubPlace, 'idno':idno, 'availability':availability, 'p':p, 'date':date, 'sourceDesc':sourceDesc, 
               'biblFull':biblFull, 'editionStmt':editionStmt, 'extent':extent, 'seriesStmt':seriesStmt, 'encodingDesc':encodingDesc, 
               'editorialDecl':editorialDecl, 'list':list, 'head':head, 'item':item, 'label':label, 'term':term, 'profileDesc':profileDesc, 
               'langUsage':langUsage, 'language':language, 'handList':handList, 'hand':hand, 'revisionDesc':revisionDesc, 'change':change, 
               'text':text, 'body':body, 'div1':div1, 'xref':xref, 'milestone':milestone, 'div2':div2, 'note':note, 'expan':expan, 
               'add':add, 'lb':lb, 'del':dell, 'space':space, 'damage':damage, 'corr':corr, 'gloss':gloss, 'handShift':handShift }

    self.xparser = XElementParser(self.my_classes)
    #self.manuscript = self.xparser.process('data/CORP190.xml')
    self.manuscript = self.xparser.process(path)
    #del self.xparser

class TOEH265MS(MANUSCRIPT):
  def __init__(self, path):
    self.my_classes = { 'TEI.2':TEI2, 'teiHeader':teiHeader, 'fileDesc':fileDesc, 'titleStmt':titleStmt, 'publicationStmt':publicationStmt, 
               'title':title, 'editor':editor, 'respStmt':respStmt, 'resp':resp, 'name':name, 'hi':hi, 'publisher':publisher, 
               'pubPlace':pubPlace, 'idno':idno, 'availability':availability, 'p':p, 'date':date, 'sourceDesc':sourceDesc, 
               'biblFull':biblFull, 'editionStmt':editionStmt, 'extent':extent, 'seriesStmt':seriesStmt, 'encodingDesc':encodingDesc, 
               'editorialDecl':editorialDecl, 'list':list, 'head':head, 'item':item, 'label':label, 'term':term, 'profileDesc':profileDesc, 
               'langUsage':langUsage, 'language':language, 'handList':handList, 'hand':hand, 'revisionDesc':revisionDesc, 'change':change, 
               'text':text, 'body':body, 'div1':div1, 'xref':xref, 'milestone':milestone, 'div2':div2, 'note':note, 'expan':expan, 
               'add':add, 'lb':lb, 'del':dell, 'space':space, 'damage':damage, 'corr':corr, 'gloss':gloss, 'handShift':handShift }

    self.xparser = XElementParser(self.my_classes)
    #self.manuscript = self.xparser.process('data/TOEH265.xml')
    self.manuscript = self.xparser.process(path)
    #del self.xparser

class TOEH8558MS(MANUSCRIPT):
  def __init__(self, path):
    self.my_classes = { 'TEI.2':TEI2, 'teiHeader':teiHeader, 'fileDesc':fileDesc, 'titleStmt':titleStmt, 'publicationStmt':publicationStmt, 
               'title':title, 'editor':editor, 'respStmt':respStmt, 'resp':resp, 'name':name, 'hi':hi, 'publisher':publisher, 
               'pubPlace':pubPlace, 'idno':idno, 'availability':availability, 'p':p, 'date':date, 'sourceDesc':sourceDesc, 
               'biblFull':biblFull, 'editionStmt':editionStmt, 'extent':extent, 'seriesStmt':seriesStmt, 'encodingDesc':encodingDesc, 
               'editorialDecl':editorialDecl, 'list':list, 'head':head, 'item':item, 'label':label, 'term':term, 'profileDesc':profileDesc, 
               'langUsage':langUsage, 'language':language, 'handList':handList, 'hand':hand, 'revisionDesc':revisionDesc, 'change':change, 
               'text':text, 'body':body, 'div1':div1, 'xref':xref, 'milestone':milestone, 'div2':div2, 'note':note, 'expan':expan, 
               'add':add, 'lb':lb, 'del':dell, 'space':space, 'damage':damage, 'corr':corr, 'gloss':gloss, 'handShift':handShift }

    self.xparser = XElementParser(self.my_classes)
    #self.manuscript = self.xparser.process('data/TOEH265.xml')
    self.manuscript = self.xparser.process(path)
    #del self.xparser


class CORP265MS(MANUSCRIPT):
  def __init__(self, path):
    self.my_classes = { 'TEI.2':TEI2, 'teiHeader':teiHeader, 'fileDesc':fileDesc, 'titleStmt':titleStmt, 'publicationStmt':publicationStmt, 
               'title':title, 'editor':editor, 'respStmt':respStmt, 'resp':resp, 'name':name, 'hi':hi, 'publisher':publisher, 
               'pubPlace':pubPlace, 'idno':idno, 'availability':availability, 'p':p, 'date':date, 'sourceDesc':sourceDesc, 
               'biblFull':biblFull, 'editionStmt':editionStmt, 'extent':extent, 'seriesStmt':seriesStmt, 'encodingDesc':encodingDesc, 
               'editorialDecl':editorialDecl, 'list':list, 'head':head, 'item':item, 'label':label, 'term':term, 'profileDesc':profileDesc, 
               'langUsage':langUsage, 'language':language, 'handList':handList, 'hand':hand, 'revisionDesc':revisionDesc, 'change':change, 
               'text':text, 'body':body, 'div1':div1, 'xref':xref, 'milestone':milestone, 'div2':div2, 'note':note, 'expan':expan, 
               'add':add, 'lb':lb, 'del':dell, 'space':space, 'damage':damage, 'corr':corr, 'gloss':gloss, 'handShift':handShift }

    self.xparser = XElementParser(self.my_classes)
    #self.manuscript = self.xparser.process('data/CORP265.xml')
    self.manuscript = self.xparser.process(path)
    #del self.xparser

class TOEH201MS(MANUSCRIPT):
  def __init__(self, path):
    self.my_classes = { 'TEI.2':TEI2, 'teiHeader':teiHeader, 'fileDesc':fileDesc, 'titleStmt':titleStmt, 'publicationStmt':publicationStmt, 
               'title':title, 'editor':editor, 'respStmt':respStmt, 'resp':resp, 'name':name, 'hi':hi, 'publisher':publisher, 
               'pubPlace':pubPlace, 'idno':idno, 'availability':availability, 'p':p, 'date':date, 'sourceDesc':sourceDesc, 
               'biblFull':biblFull, 'editionStmt':editionStmt, 'extent':extent, 'seriesStmt':seriesStmt, 'encodingDesc':encodingDesc, 
               'editorialDecl':editorialDecl, 'list':list, 'head':head, 'item':item, 'label':label, 'term':term, 'profileDesc':profileDesc, 
               'langUsage':langUsage, 'language':language, 'handList':handList, 'hand':hand, 'revisionDesc':revisionDesc, 'change':change, 
               'text':text, 'body':body, 'div1':div1, 'xref':xref, 'milestone':milestone, 'div2':div2, 'note':note, 'expan':expan, 
               'add':add, 'lb':lb, 'del':dell, 'space':space, 'damage':damage, 'corr':corr, 'gloss':gloss, 'handShift':handShift }
    
    self.xparser = XElementParser(self.my_classes)
    self.manuscript = self.xparser.process(path)
    #del self.xparser

class CORP201MS(MANUSCRIPT):
  def __init__(self, path):
    self.my_classes = { 'TEI.2':TEI2, 'teiHeader':teiHeader, 'fileDesc':fileDesc, 'titleStmt':titleStmt, 'publicationStmt':publicationStmt, 
               'title':title, 'editor':editor, 'respStmt':respStmt, 'resp':resp, 'name':name, 'hi':hi, 'publisher':publisher, 
               'pubPlace':pubPlace, 'idno':idno, 'availability':availability, 'p':p, 'date':date, 'sourceDesc':sourceDesc, 
               'biblFull':biblFull, 'editionStmt':editionStmt, 'extent':extent, 'seriesStmt':seriesStmt, 'encodingDesc':encodingDesc, 
               'editorialDecl':editorialDecl, 'list':list, 'head':head, 'item':item, 'label':label, 'term':term, 'profileDesc':profileDesc, 
               'langUsage':langUsage, 'language':language, 'handList':handList, 'hand':hand, 'revisionDesc':revisionDesc, 'change':change, 
               'text':text, 'body':body, 'div1':div1, 'xref':xref, 'milestone':milestone, 'div2':div2, 'note':note, 'expan':expan, 
               'add':add, 'lb':lb, 'del':dell, 'space':space, 'damage':damage, 'corr':corr, 'gloss':gloss, 'handShift':handShift }
    
    self.xparser = XElementParser(self.my_classes)
    #self.manuscript = self.xparser.process('data/CORP201.xml')
    self.manuscript = self.xparser.process(path)
    #del self.xparser

class COTTIBA3(MANUSCRIPT):
  def __init__(self, path):
    self.my_classes = { 'TEI.2':TEI2, 'teiHeader':teiHeader, 'fileDesc':fileDesc, 'titleStmt':titleStmt, 'publicationStmt':publicationStmt, 
               'title':title, 'editor':editor, 'respStmt':respStmt, 'resp':resp, 'name':name, 'hi':hi, 'publisher':publisher, 
               'pubPlace':pubPlace, 'idno':idno, 'availability':availability, 'p':p, 'date':date, 'sourceDesc':sourceDesc, 
               'biblFull':biblFull, 'editionStmt':editionStmt, 'extent':extent, 'seriesStmt':seriesStmt, 'encodingDesc':encodingDesc, 
               'editorialDecl':editorialDecl, 'list':list, 'head':head, 'item':item, 'label':label, 'term':term, 'profileDesc':profileDesc, 
               'langUsage':langUsage, 'language':language, 'handList':handList, 'hand':hand, 'revisionDesc':revisionDesc, 'change':change, 
               'text':text, 'body':body, 'div1':div1, 'xref':xref, 'milestone':milestone, 'div2':div2, 'note':note, 'expan':expan, 
               'add':add, 'lb':lb, 'del':dell, 'space':space, 'damage':damage, 'corr':corr, 'gloss':gloss, 'handShift':handShift }

    self.xparser = XElementParser(self.my_classes)
    #self.manuscript = self.xparser.process('data/CORP190.xml')
    self.manuscript = self.xparser.process(path)
    #del self.xparser

class TOEHCTA3(MANUSCRIPT):
  def __init__(self, path):
    self.my_classes = { 'TEI.2':TEI2, 'teiHeader':teiHeader, 'fileDesc':fileDesc, 'titleStmt':titleStmt, 'publicationStmt':publicationStmt, 
               'title':title, 'editor':editor, 'respStmt':respStmt, 'resp':resp, 'name':name, 'hi':hi, 'publisher':publisher, 
               'pubPlace':pubPlace, 'idno':idno, 'availability':availability, 'p':p, 'date':date, 'sourceDesc':sourceDesc, 
               'biblFull':biblFull, 'editionStmt':editionStmt, 'extent':extent, 'seriesStmt':seriesStmt, 'encodingDesc':encodingDesc, 
               'editorialDecl':editorialDecl, 'list':list, 'head':head, 'item':item, 'label':label, 'term':term, 'profileDesc':profileDesc, 
               'langUsage':langUsage, 'language':language, 'handList':handList, 'hand':hand, 'revisionDesc':revisionDesc, 'change':change, 
               'text':text, 'body':body, 'div1':div1, 'xref':xref, 'milestone':milestone, 'div2':div2, 'note':note, 'expan':expan, 
               'add':add, 'lb':lb, 'del':dell, 'space':space, 'damage':damage, 'corr':corr, 'gloss':gloss, 'handShift':handShift }

    self.xparser = XElementParser(self.my_classes)
    #self.manuscript = self.xparser.process('data/CORP190.xml')
    self.manuscript = self.xparser.process(path)
    #del self.xparser

class TOEI482(MANUSCRIPT):
  def __init__(self, path):
    self.my_classes = { 'TEI.2':TEI2, 'teiHeader':teiHeader, 'fileDesc':fileDesc, 'titleStmt':titleStmt, 'publicationStmt':publicationStmt, 
               'title':title, 'editor':editor, 'respStmt':respStmt, 'resp':resp, 'name':name, 'hi':hi, 'publisher':publisher, 
               'pubPlace':pubPlace, 'idno':idno, 'availability':availability, 'p':p, 'date':date, 'sourceDesc':sourceDesc, 
               'biblFull':biblFull, 'editionStmt':editionStmt, 'extent':extent, 'seriesStmt':seriesStmt, 'encodingDesc':encodingDesc, 
               'editorialDecl':editorialDecl, 'list':list, 'head':head, 'item':item, 'label':label, 'term':term, 'profileDesc':profileDesc, 
               'langUsage':langUsage, 'language':language, 'handList':handList, 'hand':hand, 'revisionDesc':revisionDesc, 'change':change, 
               'text':text, 'body':body, 'div1':div1, 'xref':xref, 'milestone':milestone, 'div2':div2, 'note':note, 'expan':expan, 
               'add':add, 'lb':lb, 'del':dell, 'space':space, 'damage':damage, 'corr':corr, 'gloss':gloss, 'handShift':handShift }

    self.xparser = XElementParser(self.my_classes)
    #self.manuscript = self.xparser.process('data/CORP190.xml')
    self.manuscript = self.xparser.process(path)
    #del self.xparser

class TOEP121(MANUSCRIPT):
  def __init__(self, path):
    self.my_classes = { 'TEI.2':TEI2, 'teiHeader':teiHeader, 'fileDesc':fileDesc, 'titleStmt':titleStmt, 'publicationStmt':publicationStmt, 
               'title':title, 'editor':editor, 'respStmt':respStmt, 'resp':resp, 'name':name, 'hi':hi, 'publisher':publisher, 
               'pubPlace':pubPlace, 'idno':idno, 'availability':availability, 'p':p, 'date':date, 'sourceDesc':sourceDesc, 
               'biblFull':biblFull, 'editionStmt':editionStmt, 'extent':extent, 'seriesStmt':seriesStmt, 'encodingDesc':encodingDesc, 
               'editorialDecl':editorialDecl, 'list':list, 'head':head, 'item':item, 'label':label, 'term':term, 'profileDesc':profileDesc, 
               'langUsage':langUsage, 'language':language, 'handList':handList, 'hand':hand, 'revisionDesc':revisionDesc, 'change':change, 
               'text':text, 'body':body, 'div1':div1, 'xref':xref, 'milestone':milestone, 'div2':div2, 'note':note, 'expan':expan, 
               'add':add, 'lb':lb, 'del':dell, 'space':space, 'damage':damage, 'corr':corr, 'gloss':gloss, 'handShift':handShift }

    self.xparser = XElementParser(self.my_classes)
    #self.manuscript = self.xparser.process('data/CORP190.xml')
    self.manuscript = self.xparser.process(path)
    #del self.xparser

class TOEP190(MANUSCRIPT):
  def __init__(self, path):
    self.my_classes = { 'TEI.2':TEI2, 'teiHeader':teiHeader, 'fileDesc':fileDesc, 'titleStmt':titleStmt, 'publicationStmt':publicationStmt, 
               'title':title, 'editor':editor, 'respStmt':respStmt, 'resp':resp, 'name':name, 'hi':hi, 'publisher':publisher, 
               'pubPlace':pubPlace, 'idno':idno, 'availability':availability, 'p':p, 'date':date, 'sourceDesc':sourceDesc, 
               'biblFull':biblFull, 'editionStmt':editionStmt, 'extent':extent, 'seriesStmt':seriesStmt, 'encodingDesc':encodingDesc, 
               'editorialDecl':editorialDecl, 'list':list, 'head':head, 'item':item, 'label':label, 'term':term, 'profileDesc':profileDesc, 
               'langUsage':langUsage, 'language':language, 'handList':handList, 'hand':hand, 'revisionDesc':revisionDesc, 'change':change, 
               'text':text, 'body':body, 'div1':div1, 'xref':xref, 'milestone':milestone, 'div2':div2, 'note':note, 'expan':expan, 
               'add':add, 'lb':lb, 'del':dell, 'space':space, 'damage':damage, 'corr':corr, 'gloss':gloss, 'handShift':handShift }

    self.xparser = XElementParser(self.my_classes)
    #self.manuscript = self.xparser.process('data/CORP190.xml')
    self.manuscript = self.xparser.process(path)
    #del self.xparser

class TSBOC190(MANUSCRIPT):
  def __init__(self, path):
    self.my_classes = { 'TEI.2':TEI2, 'teiHeader':teiHeader, 'fileDesc':fileDesc, 'titleStmt':titleStmt, 'publicationStmt':publicationStmt, 
               'title':title, 'editor':editor, 'respStmt':respStmt, 'resp':resp, 'name':name, 'hi':hi, 'publisher':publisher, 
               'pubPlace':pubPlace, 'idno':idno, 'availability':availability, 'p':p, 'date':date, 'sourceDesc':sourceDesc, 
               'biblFull':biblFull, 'editionStmt':editionStmt, 'extent':extent, 'seriesStmt':seriesStmt, 'encodingDesc':encodingDesc, 
               'editorialDecl':editorialDecl, 'list':list, 'head':head, 'item':item, 'label':label, 'term':term, 'profileDesc':profileDesc, 
               'langUsage':langUsage, 'language':language, 'handList':handList, 'hand':hand, 'revisionDesc':revisionDesc, 'change':change, 
               'text':text, 'body':body, 'div1':div1, 'xref':xref, 'milestone':milestone, 'div2':div2, 'note':note, 'expan':expan, 
               'add':add, 'lb':lb, 'del':dell, 'space':space, 'damage':damage, 'corr':corr, 'gloss':gloss, 'handShift':handShift }

    self.xparser = XElementParser(self.my_classes)
    #self.manuscript = self.xparser.process('data/CORP190.xml')
    self.manuscript = self.xparser.process(path)
    #del self.xparser

class TSBOC482(MANUSCRIPT):
  def __init__(self, path):
    self.my_classes = { 'TEI.2':TEI2, 'teiHeader':teiHeader, 'fileDesc':fileDesc, 'titleStmt':titleStmt, 'publicationStmt':publicationStmt, 
               'title':title, 'editor':editor, 'respStmt':respStmt, 'resp':resp, 'name':name, 'hi':hi, 'publisher':publisher, 
               'pubPlace':pubPlace, 'idno':idno, 'availability':availability, 'p':p, 'date':date, 'sourceDesc':sourceDesc, 
               'biblFull':biblFull, 'editionStmt':editionStmt, 'extent':extent, 'seriesStmt':seriesStmt, 'encodingDesc':encodingDesc, 
               'editorialDecl':editorialDecl, 'list':list, 'head':head, 'item':item, 'label':label, 'term':term, 'profileDesc':profileDesc, 
               'langUsage':langUsage, 'language':language, 'handList':handList, 'hand':hand, 'revisionDesc':revisionDesc, 'change':change, 
               'text':text, 'body':body, 'div1':div1, 'xref':xref, 'milestone':milestone, 'div2':div2, 'note':note, 'expan':expan, 
               'add':add, 'lb':lb, 'del':dell, 'space':space, 'damage':damage, 'corr':corr, 'gloss':gloss, 'handShift':handShift }

    self.xparser = XElementParser(self.my_classes)
    #self.manuscript = self.xparser.process('data/CORP190.xml')
    self.manuscript = self.xparser.process(path)
    #del self.xparser

class TCTH482(MANUSCRIPT):
  def __init__(self, path):
    self.my_classes = { 'TEI.2':TEI2, 'teiHeader':teiHeader, 'fileDesc':fileDesc, 'titleStmt':titleStmt, 'publicationStmt':publicationStmt, 
               'title':title, 'editor':editor, 'respStmt':respStmt, 'resp':resp, 'name':name, 'hi':hi, 'publisher':publisher, 
               'pubPlace':pubPlace, 'idno':idno, 'availability':availability, 'p':p, 'date':date, 'sourceDesc':sourceDesc, 
               'biblFull':biblFull, 'editionStmt':editionStmt, 'extent':extent, 'seriesStmt':seriesStmt, 'encodingDesc':encodingDesc, 
               'editorialDecl':editorialDecl, 'list':list, 'head':head, 'item':item, 'label':label, 'term':term, 'profileDesc':profileDesc, 
               'langUsage':langUsage, 'language':language, 'handList':handList, 'hand':hand, 'revisionDesc':revisionDesc, 'change':change, 
               'text':text, 'body':body, 'div1':div1, 'xref':xref, 'milestone':milestone, 'div2':div2, 'note':note, 'expan':expan, 
               'add':add, 'lb':lb, 'del':dell, 'space':space, 'damage':damage, 'corr':corr, 'gloss':gloss, 'handShift':handShift }

    self.xparser = XElementParser(self.my_classes)
    #self.manuscript = self.xparser.process('data/CORP190.xml')
    self.manuscript = self.xparser.process(path)
    #del self.xparser

class TCTH190(MANUSCRIPT):
  def __init__(self, path):
    self.my_classes = { 'TEI.2':TEI2, 'teiHeader':teiHeader, 'fileDesc':fileDesc, 'titleStmt':titleStmt, 'publicationStmt':publicationStmt, 
               'title':title, 'editor':editor, 'respStmt':respStmt, 'resp':resp, 'name':name, 'hi':hi, 'publisher':publisher, 
               'pubPlace':pubPlace, 'idno':idno, 'availability':availability, 'p':p, 'date':date, 'sourceDesc':sourceDesc, 
               'biblFull':biblFull, 'editionStmt':editionStmt, 'extent':extent, 'seriesStmt':seriesStmt, 'encodingDesc':encodingDesc, 
               'editorialDecl':editorialDecl, 'list':list, 'head':head, 'item':item, 'label':label, 'term':term, 'profileDesc':profileDesc, 
               'langUsage':langUsage, 'language':language, 'handList':handList, 'hand':hand, 'revisionDesc':revisionDesc, 'change':change, 
               'text':text, 'body':body, 'div1':div1, 'xref':xref, 'milestone':milestone, 'div2':div2, 'note':note, 'expan':expan, 
               'add':add, 'lb':lb, 'del':dell, 'space':space, 'damage':damage, 'corr':corr, 'gloss':gloss, 'handShift':handShift }

    self.xparser = XElementParser(self.my_classes)
    #self.manuscript = self.xparser.process('data/CORP190.xml')
    self.manuscript = self.xparser.process(path)
    #del self.xparser

class TOEI121(MANUSCRIPT):
  def __init__(self, path):
    self.my_classes = { 'TEI.2':TEI2, 'teiHeader':teiHeader, 'fileDesc':fileDesc, 'titleStmt':titleStmt, 'publicationStmt':publicationStmt, 
               'title':title, 'editor':editor, 'respStmt':respStmt, 'resp':resp, 'name':name, 'hi':hi, 'publisher':publisher, 
               'pubPlace':pubPlace, 'idno':idno, 'availability':availability, 'p':p, 'date':date, 'sourceDesc':sourceDesc, 
               'biblFull':biblFull, 'editionStmt':editionStmt, 'extent':extent, 'seriesStmt':seriesStmt, 'encodingDesc':encodingDesc, 
               'editorialDecl':editorialDecl, 'list':list, 'head':head, 'item':item, 'label':label, 'term':term, 'profileDesc':profileDesc, 
               'langUsage':langUsage, 'language':language, 'handList':handList, 'hand':hand, 'revisionDesc':revisionDesc, 'change':change, 
               'text':text, 'body':body, 'div1':div1, 'xref':xref, 'milestone':milestone, 'div2':div2, 'note':note, 'expan':expan, 
               'add':add, 'lb':lb, 'del':dell, 'space':space, 'damage':damage, 'corr':corr, 'gloss':gloss, 'handShift':handShift }

    self.xparser = XElementParser(self.my_classes)
    #self.manuscript = self.xparser.process('data/CORP190.xml')
    self.manuscript = self.xparser.process(path)
    #del self.xparser

class manuscript_db:
  #THESE MANUSCRIPS MUST BE SET IN ORDER INORDER FOR THE DATABASE TO WORK PROPERLY
  def __init__(self, corp201, toeh201, corp265, toeh265, corp190, toei190, bx8558, tcth8558, laud482, toep482, junius, tsboc121, cottiba3, toeh8558, toehcta3, toei482, toep121, toep190, tsboc190, tsboc482, tcth482, tcth190, toei121):
    self._CORP201MS = corp201  #document 
    self._TOEH201MS = toeh201  #assoc translation
    
    self._CORP265MS = corp265
    self._TOEH265MS = toeh265
    
    self._CORP190MS = corp190
    self._TOEI190MS = toei190
    
    self._BX8558MS = bx8558
    self._TCTH8558MS = tcth8558
    
    self._LAUD482MS = laud482
    self._TOEP482MS = toep482
    
    self._JUNIUSMS = junius
    self._TSBOC121MS = tsboc121

    self._COTTIBA3 = cottiba3 #no self translation file for cottiba3
    self._TOEH8558 = toeh8558 
    self._TOEHCTA3 = toehcta3
    self._TOEI482 = toei482
    self._TOEP121 = toep121
    self._TOEP190 = toep190
    self._TSBOC190 = tsboc190
    self._TSBOC482 = tsboc482
    self._TCTH482 = tcth482
    self._TCTH190 = tcth190
    self._TOEI121 = toei121
    self.manuscripts =  { 'D':{'document':self._CORP201MS, 'name':"Cambridge, Corpus Christi College, 201, s. XI<div class=\"super_script\"><span>med</span></div>; Winchester (Ker 48B; Gneuss 66)"}, 'C':{'document':self._CORP265MS, 'name':"Cambridge, Corpus Christi College, 265, s. XI<div class=\"super_script\"><span>med</span></div>; Worcester (Ker 53; Gneuss 73)"}, 'S':{'document':self._CORP190MS, 'name':"Cambridge, Corpus Christi College, 190, s. XI<div class=\"super_script\"><span>med</span></div>, XI<div class=\"super_script\"><span>2</span></div>; Exeter (Ker 45B, Gneuss 59)"}, 'B':{'document':self._BX8558MS, 'name':"Brussels, Bibliothéque royale, 8558-63, s. XI<div class=\"super_script\"><span>1</span></div>; southeastern (Ker 10, Gneuss 808)"}, 'Y':{'document':self._LAUD482MS, 'name':"Oxford, Bodleian Library, Laud Misc. 482, s. XI<div class=\"super_script\"><span>med</span></div>; Worcester (Ker 343; Gneuss 656)"}, 'X':{'document':self._JUNIUSMS, 'name':"Oxford, Bodleian Library, Junius 121, s. XI<div class=\"super_script\"><span>&#x00BE;</span></div>; Worcester (Ker 338; Gneuss 644)"}, 'N':{'document':self._COTTIBA3, 'name':"London, British Library, Cotton Tiberius A.iii, s. XI<div class=\"super_script\"><span>med</span></div>; Christ's Church, Canterbury Ker #286, Gneuss #363"} }
   
  # KEYS and what files they map too ... translations get tricky
  # NEED TO GET WITH ALLEN AND WRITE THE TECHNICAL SPECS FOR 
  #TRANSLATIONS RULES FOR THE GET_TRANSLATION FUNCTIONS FOR FOR FUTURE 
  #CHANGES, UPDATE, AND NEW FEATURES OTHERS MIGHT ADD 
  #
  #  KEY | FILENAME
  #--------------------
  #   D  | TOEH201.xml works - in menu
  #   C  | TOEH265.xml works - in menu
  #   S  | TOEI190.xml works - in menu
  #   S2 | TOEP190.xml works - not needed in menu  
  #   S3 | TSBOC190.xml works - not needed in menu
  #   S4 | TCTH190.xml -
  #   B  | TCTH8558.xml works - in menu 
  #   B2 | TOEH8558.xml works - not needed in menu
  #   Y  | TOEP482.xml works - in menu 
  #   Y2 | TOEI482.xml - not needed in menu
  #   Y3 | TSBOC482.xml works - not needed in menu
  #   Y4 | TCTH482.xml -
  #   X  | TSBOC121.xml works - in menu  
  #   X2 | TOEP121.xml - not needed in menu
  #   X3 | TOEI121.xml -  
  #   N  | TOEHCTA3.xml  - not needed in menu
  #   
  #
    self.translations = { 'D':{'translation':self._TOEH201MS, 'name':'Corpus 201 (D)'}, 'C':{'translation':self._TOEH265MS, 'name':'Corpus 265 (C)'}, 'S':{'translation':self._TOEI190MS, 'name':'Corpus 190 (S)'}, 'S2':{'translation':self._TOEP190, 'name':'(toep190.xml)Corpus 190 (S2)'}, 'S3':{'translation':self._TSBOC190, 'name':'(TSBOC190.xml)Corpus 190 (S3)'}, 'S4':{'translation':self._TCTH190, 'name':'Corpus 190 (S)'}, 'B':{'translation':self._TCTH8558MS, 'name':"Bx 8558 (B)"}, 'B2':{'translation':self._TOEH8558, 'name':'Bx 8558 (B2)'}, 'Y':{'translation':self._TOEP482MS, 'name':"Laud Misc. 482 (Y)"}, 'X':{'translation':self._TSBOC121MS, 'name':"Junius 121 (X)"}, 'X2':{'translation':self._TOEP121, 'name':'(toep121.xml)Junius 121 (X2)'}, 'X3':{'translation':self._TOEI121, 'name':'(toei121.xml)Junius 121 (X3)'}, 'N':{'translation':self._TOEHCTA3, 'name':"London, British Library, Cotton Tiberius A.iii, s. XI<div class=\"super_script\"><span>med</span></div>; Christ's Church, Canterbury Ker #286, Gneuss #363"}, 'Y2':{'translation':self._TOEI482, 'name':"Laud Misc. 482 (Y2)"}, 'Y3':{'translation':self._TSBOC482, 'name':'(TSBOC482.xml)Laud Misc. 482 (Y3)'}, 'Y4':{'translation':self._TCTH482, 'name':'Laud Misc. 482 (Y)'}}
   
   
   # self.manuscripts = {'D':{'document':self._CORP201MS,'translation':self._TOEH201MS, 'name':"Cambridge, Corpus Christi College, 201, s. XI<div class=\"super_script\"><span>med</span></div>; Winchester (Ker 48B; Gneuss 66)"}, 'C':{'document':self._CORP265MS,'translation':self._TOEH265MS, 'name':"Cambridge, Corpus Christi College, 265, s. XI<div class=\"super_script\"><span>med</span></div>; Worcester (Ker 53; Gneuss 73)"}, 'S':{'document':self._CORP190MS,'translation':self._TOEI190MS, 'name':"Cambridge, Corpus Christi College, 190, s. XI<div class=\"super_script\"><span>med</span></div>, XIï¿½; Exeter (Ker 45B, Gneuss 59)"}, 'B':{'document':self._BX8558MS, 'translation':self._TCTH8558MS, 'name':"Brussels, BibliothÃ©que royale, 8558-63, s. XI<div class=\"super_script\"><span>1</span></div>; southeastern (Ker 10, Gneuss 808)"}, 'Y':{'document':self._LAUD482MS, 'translation':self._TOEP482MS, 'name':"Oxford, Bodleian Library, Laud Misc. 482, s. XI<div class=\"super_script\"><span>med</span></div>; Worcester (Ker 343; Gneuss 656)"}, 'X':{'document':self._JUNIUSMS,'translation':self._TSBOC121MS, 'name':"Oxford, Bodleian Library, Junius 121, s. XI<div class=\"super_script\"><span>ï¿½</span></div>; Worcester (Ker 338; Gneuss 644)"}, 'N':{'document':self._COTTIBA3, 'translation':None, 'name':"London, British Library, Cotton Tiberius A.iii, s. XI<div class=\"super_script\"><span>med</span></div>; Christ's Church, Canterbury Ker #286, Gneuss #363"}}
    #
    #  ALL STYLES HAVE BEEN MOVED TO MAIN.CSS these are kept here to keep backwards compatability with the "--msp" command
    # 
    self.marginLeft_style='''
          span.marginLeft
          {
          position: absolute;
          left: 5%;
          color: blue;
          font-size: 11pt;
          }
          '''
    self.marginRight_style='''
          span.marginRight
          {
          position: relative;
          left: 100%;
          color: blue;
          font-size: 11pt;
          }
          '''
    self.add_center_style='''
          span.center
          {
          align: center;
          position: relative;
          color: blue;
          font-size: 11pt;
          }
          '''
    self.add_inline_style='''
          span.inline
          {
          position: relative;
          left: 1pt;
          bottom: 4pt;
          color: blue;
          font-size: 12pt;
          }
          '''
    self.add_interlinear_style='''
          span.interlinear
          {
          position: relative;
          bottom: 4pt;
          color: blue;
          font-size: 12pt;
          }
          '''
    self.add_general_style='''
          span.add
          {
          position: relative;
          color: blue;
          font-size: 11pt;
          }
          '''
    self.line_number_style='''
	  span.lineno
	  {
	  color: red;
	  position: relative;
	  font-size: 11px;
          cursor: default; 
	  }
	  '''
    self.page_marker_style='''
	  div.pagemarker
	  {
	  position: relative;
	  left: 15%;
	  color: maroon;
	  }	  
	  span.innerpagemarker
	  {
	  position: relative;
	  left: 90%;
	  }
	  '''
    self.character_style ='''
	  span.redfilled
	  {
	  position: absolute;	  
	  top: 0px;
          color: red;	  
          z-index: 2;
	  }
          span.redfilledinner
          {
	  position: relative;
          align: left;
          left: .04em;
          color: black;          	          
	  z-index: 1;
          }
	  span.blackfilled
	  {
	  position: absolute;
	  color: black;
	  z-index: 2;	  
	  }
	  span.blackfilledinner
	  {
	  position: relative;
	  font-weight: strong;
	  align: left;
	  left: 2.45pt;
	  color: darkgray;
	  z-index: 1;						  
	  }
	  span.greenfilled
	  {
	  position: absolute;
	  color: green;
	  z-index: 2;
	  }
	  span.greenfilledinner
	  {
	  position: relative;
	  color: black;
	  font-weight: bold;
	  z-index: 1;
	  }
	  span.orncap2
	  {
	    font-size: 25pt;
	  }
	  span.orncap3
	  {
	    font-size: 34pt;
	  }
	  span.orncap4
	  {
	    font-size: 54pt;
	  }
	  span.orncap5
	  {
	    font-size: 17px;
	  }
	  span.red
	  {
	  color: red;
	  }
	  span.green
	  {
	  color: green;
	  }
	  span.od
	  {
	  position: relative;
          left: -15px;
          top: 50%;
	 
	  }
	  span.orncap8
	  {
	  font-size: 85pt;
	  position: relative;
	  top: 15px;
	  }
	  span.aelig2
	  {
	   font-weight: strong;
	   font-size: 20pt;
	  }
          span.blue
          {
          color: blue;
          }
          span.underlined
          {
          text-decoration: underline;
          }
	  span.a2
	  {
	  font-weight: strong;
	  font-size: 20pt;
	  }
	  span.e2
	  {
	  font-weight: strong;
	  font-size: 20pt;
	  }
	  span.d2
	  {
	  font-weight: strong;
	  font-size: 20pt;
	  }
	  span.ash2
	  {
	  font-size: 20px;
	  color: black;
	  font-weight: strong;
	  }
          '''
    self.add_style='''
	  span.del
	  {
	  color: #008080;
	  }
          '''
    self.damage_style='''
	  span.damage
	  {
	  color: #800080;
	  }
	  '''
    self.milestone_style='''
	  div.chaptermarker
	  {
	  position: relative;
	  left: 15%;
	  color: #808000;
	  }
	  span.innerchaptermarker
	  {
	  position: relative;
	  left: 90%;
	  }
	  '''
    self.single_ms_style='''
	  
	  body
	  {
	  font-family: sans-serif;
	  }
	  span.div2
	  {
	  z-index: 0;
	  }
	  '''
    self.menu_style='''
          table.menu
	  {
	  border: 1px;
	  border-color: black;
	  }
	  table.menu td:hover
	  {
	  color: white;
	  background-color: blue;
	  }	  
          table.close
	  {
	  border: 1pt;
	  border-color: white;
	  position: relative;
	  left: 2pt;
	  font-weight: bold;
	  }								
	  table.close td
	  {	  
	  cursor: pointer;
	  }
          table.close td:hover
	  {
	  color: #626C9B;
	  background-color: white;
	  font-weight: bold;
	  }						  
          table.title
	  {
	  padding-left:2px;
	  font-size: 8px;
	  background-color: #003399;
	  }				 	  	   
          a.menulink
	  {
	   display: inline;
	   padding-left: 60px;
	   padding-right: 60px;
	  }
	  a.menu:hover
	  {
	  color: darkblue;
	  text-decoration: none;
	  }
	  a.menu:visited
	  {
	  color: darkblue;
	  text-decoration: none;
	  }
          ul.LineNumberMenu, ul.LineNumberMenu
          {
          list-style-type: none;
          display: block;         
	  cursor: default;
          padding: 0;
          margin: 0;
	  width: 40px;
          }
	  ul.LineNumberMenu li
	  {
	  list-style-type: none;
	  margin: 0;
	  padding: 0;
	  position: relative;	 
	  
	  left: -4px;
	  }
	  ul.LineNumberMenu li div
	  {
	  background-color: darkblue;
	  width: 165px;
	  height: 18px;
	  border: 1px;
	  top: -1px;
	  }
	  ul.LineNumberMenu li div div, ul.LineNumberMenu li > ul li div div, ul.LineNumberMenu li > ul li > ul li div div
	  {
	  background-color: white;
	  color: darkblue;
	  height: 16px;
	  width: 163px;
	  align: right;
	  position: relative;
	  top: 1px;
	  left: 1px;
          z-index: 1000;
	  }	  
	  ul.LineNumberMenu li div div span
	  {
	  position relative;
	  font-size 17pt;
	  }
	  ul.LineNumberMenu li > ul
	  {
	    display: none;
            position: absolute;
	   
	  }
	  ul.LineNumberMenu li  div.quicktranslation
	  {
	  display: none;
	  }
	  
	  ul.LineNumberMenu li:hover div.quicktranslation
	  {
	  display: block;
	  position: absolute;
	  top: 60px;
	  width: 400px; 
	  }
	  ul.LineNumberMenu li:hover div.quicktranslation div
	  {
	  position: relative;
	  top: 0px;
	  left: 0px;	  
	  width: 400px;
          }
	  ul.LineNumberMenu li:hover > ul li div.alltranslation
	  {
	  display: none;
	  }
	  ul.LineNumberMenu li:hover > ul li:hover div.alltranslation
	  {
	  display: block;
	  position: absolute;
	  top: 0px;
	  }
	  ul.LineNumberMenu li:hover div, ul.LineNumberMenu li:hover > ul li:hover div, ul.LineNumberMenu li:hover > ul li:hover  > ul li:hover div
	  {
	  background-color: darkblue;
	  }
	  ul.LineNumberMenu li:hover div div, ul.LineNumberMenu li:hover > ul li:hover div div, ul.LineNumberMenu li:hover > ul li:hover  > ul li:hover div div
	  {
	  background-color: darkblue;
	  }
	  ul.LineNumberMenu li:hover > ul li div div, ul.LineNumberMenu li:hover > ul li:hover  > ul li div div a
	  {
	  text-decoration: none;
	  color: darkblue;
	  }
	  ul.LineNumberMenu li:hover div div, ul.LineNumberMenu li:hover > ul li:hover div div, ul.LineNumberMenu li:hover > ul li:hover  > ul li:hover div div a
	  {
	  color: #E5ECFF;
	  }
	  ul.LineNumberMenu li:hover > ul li div
	  {
	  background-color: darkblue;
	  }
	  ul.LineNumberMenu li:hover > ul li div div, ul.LineNumberMenu li:hover > ul li:hover  > ul li div div	  
	  {
	  background-color: white;
	  }
          ul.LineNumberMenu li > ul li div div, ul.lineNumberMenu li > ul li > ul li div div
          {
          z-index: 1000;
          }					
	  ul.LineNumberMenu li:hover > ul
	  {
	  display: block;
	  top: 0px;
	  left: 128px;
	  }
	  .menu
	  {
	  visibility: hidden;
	  position: absolute;
	  top: 30px;
	  left: 85%;
	  font: 12px verdana,arial,helvetica;
	  color: #ffffff;
	  background: #000000;
	  padding: 10px;
	  border: none;
	  z-index: 5;
	  }
	  '''
    self.line_table_style='''
          body
	  {
	   overflow: scroll;
	  }
	  div.viewall
	  {
	  visibility: block;
	  position: absolute;
	  top: 0;
	  left: 0;;	  
	  min-width: 800px;
	  padding: 2px;
	  z-index: 5;
	  background-color: darkblue;
	  }
	  table#viewall
	  {
	   position: relative;
	   padding: 0;
	   border: 0px;
	   color: white;
	   background-color: #E5ECFF;
	   height: 100%;	   
	  }
	  table#viewall tr#header, table#viewall tr#header2
	  {
	    height: 10px;
	    background-color: darkblue;
	    color: white;
	    font-size: 14px;	    
	    font-family: arial, sans serif;
	    padding: 0;
	  }
	  b#btitle
	  {
	   font-size: 14pt;
	   color: white;
	   font-family: sans-serif, arial;
	   font-weight: bold;
	  }
	  table#viewall table#versontitle, table#viewall table#versontitle2
	  {
	   color: white;
	   font-weight: bold;
	   background-color: darkblue;
	  }
	  table#viewall table.close tr td
	  {
	  text-decoration: none;
	  font-weight: bold;
	  color: white;
          align: center;
	  }
          table#viewall table.close tr td div
          {
          position: relative;
          top: 0px;
          }
	  table#viewall table.close table
	  {
	  background-color: darkblue;
	  }
	  table#viewall table.close 
	  {
	  padding: 0;
	  }
	  table#viewall table.close:hover td
	  {
	  background-color: white;
	  color: darkblue;
	  }	  
	  table#viewall table#content
	  {
	  valign: top;
	  background-color: #E5ECFF;
	  padding: 2px;
	  }
	  table#viewall table#content tr
	  {
	  background-color: #E5ECFF;
	  }
	  table#viewall table#content td
	  {
	   background-color: lightyellow;
	  }
	  table#viewall table#content td#vline 
	  {
	  width: 5%;
	  }
	  table#viewall table#content table#version div
	  {
	   background-color: lightyellow;
	   position: relative;
	   left: 10%;
	  }
	  table#linenotable
	  {
	  position: relative;
	  left: 20px;
	  top: -7px;
	  background-color: darkblue;
	  padding: 3px;
	  }
	  table#linenotable tr td
	  {
	  background-color: #E5ECFF;
	  padding: 0;
	  }
	  span#linenospan
	  {
	   position: static;
	   background-color: #E5ECFF;
	   padding: 0px;	   
	  }
	  b#lineno
	  {
	  color: red;
	  background-color: #E5ECFF;
	  position: relative;
          top: -4px;
	  z-index: 3;
	  padding: 2px;
	  }
	  b#lineno2
	  {
          display: none;
	  color: #553355;
	  background-color: #553355;
	  position: relative;
	  left: -94px;
	  z-index: 2;
	  padding: 4px;
	  }
	  table#blueborder
	  {
	  width: 100%;
	  padding: 1px;
	  background-color: darkblue;
	  }
	  '''
        
    #setup a style dictionary
    self.styles = {"marginLeft_style":{"single":self.marginLeft_style}, "marginRight_style":{"single":self.marginRight_style}, "add_center_style":{"single":self.add_center_style}, "add_inline_style":{"single":self.add_inline_style}, "add_interlinear_style":{"single":self.add_interlinear_style}, "add_general_style":{"single":self.add_general_style}, "line_number_style":{"single":self.line_number_style}, "page_marker_style":{"single":self.page_marker_style}, "character_style":{"single":self.character_style}, "add_style":{"single":self.add_style}, "damage_style":{"single":self.damage_style}, "milestone_style":{"single":self.milestone_style}, "single_ms_style":{"single":self.single_ms_style}, "menu_style":{"single":self.menu_style}, "line_table_style":{"single":self.line_table_style}}
  
  def get_MS_list(self):
    return self.manuscripts
  def get_line_version(self, key, line_number):  
   MS = self.get_MS_list()[key]['document']
   return MS.get_line_version(line_number)

  def get_MS_name(self, MS_key, translation=False):
    if translation:
      return self.translations[MS_key]['name']
    else:
      return self.manuscripts[MS_key]['name']

  def get_one_MS_style(self):
    style =""
    for key in self.styles:
          style += self.styles[key]["single"]
    return style

  def get_all_MS_paged(self):
    global CURRENT_MS_KEY
    for key in self.manuscripts:
      CURRENT_MS_KEY = key
      MS = self.manuscripts[key]['document'].manuscript
      texts = MS.getChildren("text")
      body = texts[0].getChildren('body')
      body[0].BodytoHTML_paged(self)
  #
  # get_one_MS_paged will recurrsively render the manuscript but break each page into pages by the defining page markers
  # this function will not return anything and all text will be written to the CURRENT_FILE object which is used to controll
  # file output based on page markers
  #
  def get_one_MS_paged(self, ms_key):
    global CURRENT_MS_KEY
    CURRENT_MS_KEY = ms_key
    MS = self.manuscripts[ms_key]['document'].manuscript
    texts = MS.getChildren("text")
    body = texts[0].getChildren('body')
    body[0].BodytoHTML_paged(self)
  
  def get_translation_paged(self, ms_key): #get translation for view in translation page
    global CURRENT_MS_KEY
    CURRENT_MS_KEY = ms_key
    MS = self.translations[ms_key]['translation'].manuscript
    texts = MS.getChildren("text")
    body = texts[0].getChildren('body')
    body[0].BodytoHTML_tpaged(self)
    
  def get_one_MS(self, manuscript_key):
    #find the correct manuscript and return the html
    #database = manuscript_db()
    use_key = manuscript_key
    #return "DEBUG: "+str(type(self.manuscripts))
    MS = self.manuscripts[use_key]['document'].manuscript
    #header = MS.getChildren("teiHeader")
    texts = MS.getChildren("text")
    temp =[]
    body = texts[0].getChildren('body')
    """
    style = '''
             <head>
	     <script language="JavaScript" type="text/javascript" src="/OE/moving_table.js">
	     </script>
	     <style>
            '''	    
    """
    #for key in self.styles:
    #  style += self.styles[key]["single"]
    """
    style += '''
             </style>
	     </head>
	     '''
    """
    #page = '<html>'
    #page += style
    #page += '<body bgcolor="lightyellow">'
    #page += '<scriptlanguage="JavaScript" src="/OE/new_window.js"></script>'
    """
    page += '''
            <script language="JavaScript">
	    <!-- 
	    function open_new_window(url)
	    { 
	    new_window = window.open(url,'Viewall','toolbar=no,scrollbars=yes,menubar=no,resizable=yes,dependent=no,status=yes,width=80,height=60,left=100,top=100')
	    }
	    // New window attributes
	    // url - the variable for the url of the page in the new window
	    // that is passed by placing it single-quoted in either the link or form
	    // window_name - the name of the new window being opened
	    // width - width of the new window in pixels
	    // height - height of the new window in pixels
	    // top - the new widow top will appear xx number of pixels from the top of the screen
	    // left - the new widow left margin will appear xx number of pixels from the left of the screen

	    // The following attributes will suppress the respective window elements
	    // when the value is set to zero or if omitted. When listed or equal to one
	    // the window attribute will appear
	    // toolbar,menubar,resizable,dependent,status
	    // -->
	    </script>
            '''

    page += '<center><table width="98%" id="page" style="min-width: 900px;"><tr><td><table width="75%" cellpadding="5" border="0" align="center"><tr><td><table border="0" cellpadding="0" align="center"><tr><td>'"""
    page = body[0].BodytoHTML(self)
    """
    page += "</td></tr></table></td></tr></table></td></tr></table></center>"
    page += '<div style="height: 200px;">&nbsp</div>'
    page += '<script language="JavaScript" type="text/javascript" src="/OE/moving_table.js"></script>'
    page += '<script language="JavaScript" type="text/javascript" src="/OE/wz_tooltip.js"></script>'
    page += "</body>"
    page += "</html>"
    """
    
    return page
             
    

		
  def get_two_MS(self, manuscript_key):
    #find the 2 manuscripts to display side by side/
    pass
    
  def get_line_table(self, cur_line_number):
    MS_key = cur_line_number[0]
    search_line = cur_line_number[1:len(cur_line_number)]
    line_in_other_MSS = []
    for key in self.manuscripts: # find line numbers in other docs      
      if MS_key != key: #don't add our current document to search        #search for line        
        if self.manuscripts[key]['document'].has_line(search_line):          
	   key_found = key+search_line          
	   line_in_other_MSS.append(key_found)

    line_table_checkboxes = '<span style="position: relative; top: 6px;font-size: 12px; background-color: #E5ECFF; padding: 0px;"><form style="color: black;"><span style="margin: 1em; color: black;"><b style="letterspacing: .1em; font-size: 12pt;">View/Hide Canon:</b></span>'
    line_table_checkboxes += '<span onmouseover="javascript:tbl= new getObj(\''+cur_line_number+'tr\')" style="margin: 1em; color: black;"><input TYPE="checkbox" VALUE="" onclick="javascript:hide_line()" checked>'+cur_line_number+'</span>'
    for line in line_in_other_MSS:
      line_table_checkboxes += '<span onmouseover="javascript:tbl= new getObj(\''+line+'tr\')"style="margin: 1em; color: black;"><input TYPE="checkbox" VALUE="" onclick="javascript:hide_line()" checked>'+line+'</span>'
    line_table_checkboxes += '</form></span>'
    line_table = '''
                 <div id="view1" class="viewall" width="javascript:display.width -1px;">
		   <table id="viewall" cellspacing="0" valign="top" height="100%" width="100%">
		     <tr id="header">
		       <td>
		         <table id="versiontitle" width="100%">
			   <tr>
			     <td style="color: white;">&nbsp;<b id="btitle">'''+cur_line_number+'''</b></td>
			     <td align="right" valign="center">
			       <div id="close" valign="center">
			         <table id="close" style="font-size: 14px; cursor: pointer;" title="Click to close this view." onclick="javascript:window.close()">
				   <tr valign="center"><td><div>&nbsp;X&nbsp;</div></td></tr>
				 </table>
			       </div>
			     </td>
			   </tr>
			 </table>
		       </td>
		     </tr>
		     <tr valign="top" bgcolor="#E5ECFF">
		       <td bgcolor="#E5ECFF" style="min-height: 500px;">
		         <table align="center" valign="top" cellspacing="2px" width="100%" id="content">
		           <tr bgcolor="#E5ECFF">
			     <td bgcolor="#E5ECFF">
			       <table style="background-color: darkblue; padding: 1px; width: 100%;">
			        <tr bgcolor="#E5ECFF">
				  <td bgcolor="#E5ECFF">'''+line_table_checkboxes+'''</td>
				</tr>
			       </table>
			     </td>
			   </tr>
			   <tr valign="top" id="'''+cur_line_number+'''tr" bgcolor="#E5ECFF">
			     <td>
			       <table id="blueborder">
			         <tr bgcolor="#E5ECFF">
				   <td bgcolor="#E5ECFF">
				     <table bgcolor="lightyellow" valign="top" class="version">
				       <tr height="20px">
				         <td id="linetitle">
					   <table id="linenotable" cellspacing="0">
					     <tr>
					       <td>
					         <span id="linenospan"><b id="lineno">&nbsp;'''+cur_line_number+'''&nbsp;</b></span>
					       </td>
					     </tr>
					   </table>
					 </td>
				       </tr>
				       <tr>
				         <td  bgcolor="lightyellow">'''+self.get_line_version(MS_key, cur_line_number)+'''</td>
				       </tr>
				     </table>
				   </td>
				 </tr>
			       </table>
			     </td>
			   </tr>'''
    #lines_entered += 1
    for line in line_in_other_MSS:
      line_insert = self.get_line_version(line[0], line)
      line_table += '''    <tr id="'''+line+'''tr">
                             <td>
			       <table id="blueborder">
			         <tr>
				   <td>
				     <table valign="top" class="version">
				       <tr height="20px">
				         <td id="linetitle">
					   <table id="linenotable" cellspacing="0">
					     <tr>
					       <td><span id="linenospan"><b id="lineno">&nbsp;'''+line+'''&nbsp;</b></span></td>
					     </tr>
					   </table>
					 </td>
				       </tr>
				       <tr>
				         <td>'''+line_insert+'''</td>
				       </tr>
				     </table>
				   </td>
				 </tr>
			       </table>
			     </td>
			   </tr>'''
      
    line_table += '''    </table>
                       </td>
		     </tr>
		     <tr bgcolor="darkblue">
		       <td bgcolor="darkblue">
		         <table id="versiontitle2" width="100%" bgcolor="darkblue">
			   <tr id="header2" style="max-height: 10px;">
			     <td style="color: white;">&nbsp;<b id="btitle">'''+cur_line_number+'''</b></td>
			     <td align="right" valign="center">
			       <div id="close" valign="center">
			         <table id="close" style="font-size: 14px; cursor: pointer;" title="Click to close this view." onclick="javascript:window.close()">
				   <tr valign="center"><td><div>&nbsp;X&nbsp;</div></td></tr>
				 </table>
			       </div>
			     </td>
			   </tr>
			 </table>
		       </td>
		     </tr>
		   </table>
		 </div>'''
    return_text = '''
                   <html>
		   <head>		   
		   <script LANGUAGE="JavaScript">
		     var sw = screen.width*.9;
		     var sh = screen.height*.65;
		     javascript:window.resizeTo(sw,sh);
		     var x = (screen.width-sw)/2;
		     var y = (screen.height-sh)/2;
		     window.moveTo(x,y);
		   </script>
		   <style>		   
		   '''
    for key in self.styles:
       return_text += self.styles[key]["single"]
    return_text +='''
		   </style>
		   </head>		   		   		   
		   <body bgcolor="lightyellow"><script language="JavaScript" type="text/javascript" src="/OE/moving_table.js"></script>
		   '''+line_table+'''
		   <script language="JavaScript" type="text/javascript" src="/OE/wz_tooltip.js"></script>
		   </body>
		   </html>
                  '''
    return return_text
    
  def remove_filler(self, text): #takes out the '<-*->' in the getText
     pos = text.find('<-*->')
     if False: # True:
       print '<br/>DEBUG<br/>'
       print 'pos: '+str(pos)+'<br/>'
     new_text = ""
     if pos != -1:
       if pos != 0:
          new_text += text[0:pos]
          new_text += ""
          new_text += self.remove_filler(text[pos+5:len(text)])
       else:
         new_text += ""
         new_text += self.remove_filler(text[5:len(text)])
     else:
       new_text += text
     if False:
       print '<br/>DEBUG<br/>'
       print 'Orig. Text: ' +text+'<br/>'
       print 'New_text: '+new_text+'<br/>'
       print '<br/>'
     return new_text
  
  def replace_text(self, find_text, replace_with_text, search_text):
     text = search_text
     pos = text.find(find_text)
     find_text_length = len(find_text)
     if False: # True:
       print '<br/>DEBUG<br/>'
       print 'pos: '+str(pos)+'<br/>'
     new_text = ""
     if pos != -1:
       if pos != 0:
          new_text += text[0:pos]
          new_text += replace_with_text
          new_text += self.replace_text(find_text, replace_with_text, text[pos+find_text_length:len(text)])
       else:
         new_text += replace_with_text
         new_text += self.replace_text(find_text, replace_with_text, text[find_text_length:len(text)])
     else:
       new_text += text
     if False:
       print '<br/>DEBUG<br/>'
       print 'Orig. Text: ' +text+'<br/>'
       print 'New_text: '+new_text+'<br/>'
       print '<br/>'
     return new_text
     
  def get_translation_from_other_version(self, MS_key, line_number):
    #print "Looking else where...<br/>"
    for key in self.manuscripts:
      if key != MS_key:
        text = self.get_translation(key, line_number)
	if text != "" and text != None:
	  #temp_text = "Found alternate Translation for canon "+line_number+" in manuscript "+key+"<br/>"	
	  temp_text = "[<b>Translated from manuscript "+key+"</b>]<br/>"+text
	  return [key, temp_text]
      
    return []
   

  #
  # THIS FUNCTION RETURNS A LIST IN THE FORMAT
  # [ ms key where translation is found( single char ), translation text ]
  #
  def get_translation(self, line_number, set_escapes, text_only=True):
    DEBUG = False
    if DEBUG:
      print "DEBUG: text_only ="+str(text_only)
    MS_key = line_number[0]
    found_key = ""
    trans_text = ""
    first_num_text = line_number[1:3]
    first_num = int(first_num_text)
    #SELF TRANSLATION FOR THE FOLLOWING CANONS
    #undecided -- S0 - S34
    #S70 - S78
    #D50-D56
    #X01-X27
    #Y40-Y45
    #Y80-90
    #C50-C55
    #B60-B80
    import re
    text_test = re.compile("[a-zA-Z0-9]*")
    
    if str(line_number) == 'B44.29.03':
      print "HEY!!!!", TRANS_LPDB.get_key_of_trans_map(line_number)
    MS_key = TRANS_LPDB.get_key_of_trans_map(line_number)
    if MS_key != "Not Found!":
      trans_text = self.get_translation2(MS_key, line_number, set_escapes, text_only)
    #print "BUILD LINE NUMBER "+str( line_number )
   
    if (len(MS_key) == 1 and MS_key == 'S' and first_num > 29 and first_num < 36) or (MS_key == 'S' and first_num > 69 and first_num < 80) or (MS_key == 'D' and first_num > 49 and first_num < 57) or (MS_key == 'X' and first_num > 0 and first_num < 28) or (MS_key == 'Y' and first_num > 39 and first_num < 46) or (MS_key == 'Y' and first_num > 79 and first_num < 91) or (MS_key == 'C' and first_num > 49 and first_num < 57) or (MS_key == 'B' and first_num > 59 and first_num < 81):    
      print "DEBUG !!!! - "+str(line_number)
      if line_number == 'X33.01.00':
        print str(line_number)+" - "+str(TRANS_LPDB.get_key_of_trans_map(line_number))
      if TRANS_LPDB.get_key_of_trans_map(line_number) != 'Not Found!':
        MS_key = TRANS_LPDB.get_key_of_trans_map(line_number)  

      if self.translations.has_key(MS_key):
        trans_text = self.get_translation2(MS_key, line_number, set_escapes, text_only)
       
      #if canon is C or D and is not found for any reason check the other (e.g. not MS D translation not found check C.  This is for all C and D CANON#'s 50-55)
      #print "DEBUG: MS_key: "+str(MS_key)+" canon - "+str( line_number )
      #print str(trans_text.find('a') == -1 and trans_text.find('e')  == -1 and trans_text.find('i')  == -1 and trans_text.find('o')  == -1 and trans_text.find('u') == -1)
      #print "TRANS_TEXT: "+str( trans_text )
      
      #print str(text_test.match(trans_text) != None )
      #if trans_text.find('a') == -1 and trans_text.find('e')  == -1 and trans_text.find('i')  == -1 and trans_text.find('o')  == -1 and trans_text.find('u') == -1:
      if not text_test.match(trans_text):	
	if MS_key == 'D':
	  MS_key = 'C'
	  if self.translations.has_key(MS_key):
            trans_text = self.get_translation2(MS_key, line_number, set_escapes, text_only)
	elif MS_key == 'C':
	  MS_key = 'D'
	  if self.translations.has_key(MS_key):
	    trans_text = self.get_translation2(MS_key, line_number, set_escapes, text_only)
    # COTTIBA3 translations
    elif (MS_key == 'N'):
      if TRANS_LPDB.get_key_of_trans_map(line_number) != 'Not Found!':
        MS_key = TRANS_LPDB.get_key_of_trans_map(line_number)
        if self.translations.has_key(MS_key):	
	  trans_text = self.get_translation2(MS_key, line_number, set_escapes, text_only)
      
      ''' #REMOVED TO TRY NEW SEARCH METHOD FOR CORRECT TRANSLATION
      if (first_num < 56 and first_num > 50):
        MS_key = 'D'
        if self.translations.has_key(MS_key):	
	  trans_text = self.get_translation2(MS_key, line_number, set_escapes, text_only)
      elif (first_num < 35 and first_num > 30):
        MS_key = 'S'
	if self.translations.has_key(MS_key):	
	  trans_text = self.get_translation2(MS_key, line_number, set_escapes, text_only)
      '''  
    # S01-S27 and Y01-Y27  
    elif ((MS_key == 'S' or MS_key == 'Y') and first_num > 0 and first_num < 28):
      if MS_key == 'S' and TRANS_LPDB.get_key_of_trans_map(line_number) != 'Not Found!':
        MS_key = TRANS_LPDB.get_key_of_trans_map(line_number)
	print "MS_key mask is: "+str(MS_key)
	if self.translations.has_key(MS_key):
          trans_text = self.get_translation2(MS_key, line_number, set_escapes, text_only)
      else:
        MS_key = 'X'
        if self.translations.has_key(MS_key):	
          trans_text = self.get_translation2(MS_key, line_number, set_escapes, text_only)
    #elif (MS_key == 'S') and first_num > 39 and first_num < 46:
     #MS_key = TRANS_LPDB.get_key_of_trans_map( line_number )
     #print "DEBUG MS_key mask: "+MS_key
     #if self.translations.has_key( MS_key ):
     #   trans_text = self.get_translation2(MS_key,line_number, set_escapes, text_only)
    #S40-S45, B40-B45, and X40-X45
    elif ((MS_key == 'S' or MS_key == 'B' or MS_key == 'X') and first_num > 39 and first_num < 46):
      if MS_key == 'S':
        print "CHECKING line(DEBUG): "+str(line_number)+" "+str(TRANS_LPDB.get_key_of_trans_map(str(line_number)))
      if MS_key == 'S' and TRANS_LPDB.get_key_of_trans_map(line_number) != 'Not Found!':
        MS_key = TRANS_LPDB.get_key_of_trans_map(line_number)
	if self.translations.has_key(MS_key):
         trans_text = self.get_translation2(MS_key, line_number, set_escapes, text_only)
      else:
        MS_key = 'Y'
        if self.translations.has_key(MS_key):
          trans_text = self.get_translation2(MS_key, line_number, set_escapes, text_only)
    #B30-B35, X30-X35, Y30-Y35, and N30-N35
    elif ((MS_key == 'B' or MS_key == 'X' or MS_key == 'Y' or MS_key == 'N') and first_num > 29 and first_num < 36):
      MS_key = 'S'
      if self.translations.has_key(MS_key):
        trans_text = self.get_translation2(MS_key, line_number, set_escapes, text_only)
    #B50-B56, X50-X56, Y50-Y56, and N50-N56
    elif ((MS_key == 'B' or MS_key == 'X' or MS_key == 'Y' or MS_key == 'N') and first_num > 49 and first_num < 57):
      MS_key = 'D' #start by translating with D
      if self.translations.has_key(MS_key):
        trans_text = self.get_translation2(MS_key, line_number, set_escapes, text_only)
      #if translation not found in D check C
      if trans_text.find('a') == -1 and trans_text.find('e')  == -1 and trans_text.find('i')  == -1 and trans_text.find('o')  == -1 and trans_text.find('u') == -1:
        MS_key = 'C'
	if self.translations.has_key(MS_key):
	  trans_text = self.get_translation2(MS_key, line_number, set_escapes, text_only)
    #Y60 - 83 ...experimental...ask Allen if this is correct
    elif (MS_key == 'Y' and first_num > 59 and first_num < 80):
      #print "***** TRYING TRANSLATOR MS B *****"
      if self.translations.has_key(MS_key):
        trans_text = self.get_translation2(MS_key, line_number, set_escapes, text_only)
	
    #not found: this should never happen at final product per Allen Frantzen	
    if trans_text.find('a') == -1 and trans_text.find('e')  == -1 and trans_text.find('i')  == -1 and trans_text.find('o')  == -1 and trans_text.find('u') == -1:
      return ['?', "We are sorry, this translation has not been entered in the database yet."]
    
    key_test = re.compile("[A-Z]") 
    found_key = key_test.match(MS_key).group()
      #trans_text = self.replace_text("'","\\'",trans_text)
      #trans_text = self.replace_text('"',"\\'",trans_text)
      #trans_text = self.replace_text('\n'," ",trans_text)
      #print "DEBUG: "+line_number+" "+str(trans_text.find('a'))

    return [found_key, trans_text]
    
  def get_translation2(self, MS_key, line_number, set_escapes=False, text_only=True):
    #print "<b>DEBUG key:</b> " +MS_key
    #print " <b>DEBUG line_number:</b> "+line_number+"<br/>"
    text=""
    MS = self.translations[MS_key]['translation'] #get translation
       #text += str(MS)
    #if MS['document'] == MS['translation']:
    #  text += "DEBUG: DOCUMENTS ARE THE SAME!<br/>"
    #else:
    #  text += "DEBUG: DOCUMENTS ARE NOT THE SAME!<br/>"
    #MS = MS['translation']
    if text_only:
      text += MS.get_line(line_number)
    else:
      text += MS.get_line_version(line_number)
#    if text == "":
#      

    if set_escapes:
      text = self.replace_text("'", "\\'", text)
      text = self.replace_text('"', "\\'", text)
      text = self.replace_text('\n', " ", text)
    return text
    #return "Code note working yet!"

#
# The gen_translation_table_pages will generate
# html pages like the canon table pages but with
# only the one canon and it's translation.
#
def gen_translation_table_pages(MS_key=None):
  lines_written ={}
  files_written = 0
  filename = "data/CORP201.xml"
  _CORP201MS = CORP201MS(filename)
  
  filename = "data/TOEH201.xml"
  _TOEH201MS = TOEH201MS(filename)
  
  filename = "data/CORP265.xml"
  _CORP265MS = CORP265MS(filename)
  
  filename = "data/TOEH265.xml"
  _TOEH256MS = TOEH265MS(filename)
  
  filename = "data/CORP190.xml"
  _CORP190MS = CORP190MS(filename)
  
  filename = "data/TOEI190.xml"
  _TOEI190MS = TOEI190MS(filename)
  
  filename= "data/BX8558.xml"
  _BX8558MS = BX8558MS(filename)
  
  filename = "data/TCTH8558.xml"
  _TCTH8558MS = TCTH8558MS(filename)
  
  filename = "data/LAUD482.xml"
  _LAUD482MS = LAUD482MS(filename)
  
  filename = "data/TOEP482.xml"
  _TOEP482MS = TOEP482MS(filename)

  filename = "data/JUNIUS.xml"
  _JUNIUSMS = JUNIUSMS(filename)

  filename = "data/TSBOC121.xml"
  _TSBOC121MS = TSBOC121MS(filename)
  
  filename = "data/COTTIBA3.xml"
  _COTTIBA3 = COTTIBA3(filename)

  filename = "data/TOEH8558.xml"
  _TOEH8558 = TOEH8558MS(filename)
 
  filename = "data/TOEHCTA3.xml"
  _TOEHCTA3 = TOEHCTA3(filename)
  
  filename = "data/TOEI482.xml"
  _TOEI482 = TOEI482(filename)

  filename = "data/TOEP121.xml"
  _TOEP121 = TOEP121(filename)
  
  filename = "data/TOEP190.xml"
  _TOEP190 = TOEP190(filename)
  
  filename = "data/TSBOC190.xml"
  _TSBOC190 = TSBOC190(filename)
  
  filename = "data/TSBOC482.xml"
  _TSBOC482 = TSBOC482(filename)
 
  filename = "data/TCTH482.xml"
  _TCTH482 = TCTH482(filename)

  filename = "data/TCTH190.xml"
  _TCTH190 = TCTH190(filename)
 
  filename = "data/TOEI121.xml"
  _TOEI121 = TOEI121(filename)

  database = manuscript_db(_CORP201MS, _TOEH201MS, _CORP265MS, _TOEH256MS, _CORP190MS, _TOEI190MS, _BX8558MS, _TCTH8558MS, _LAUD482MS, _TOEP482MS, _JUNIUSMS, _TSBOC121MS, _COTTIBA3, _TOEH8558, _TOEHCTA3, _TOEI482, _TOEP121, _TOEP190, _TSBOC190, _TSBOC482, _TCTH482, _TCTH190, _TOEI121)
  
  TRANS_LPDB.build_lpdb(database)
  MS_LPDB.build_lpdb(database)
  import re
  
  key_test = re.compile("[A-Z]")
  empty_line_test = re.compile("[<]div[>][<]/div[>]")
  for key in  database.manuscripts:
    if key == MS_key or MS_key == None :
      MS = database.manuscripts[key]['document'].manuscript
      current_key = key
      cur_file =""
      line_in_other_MSS = []
      texts = MS.getChildren("text") 
      bodys = texts[0].getChildren('body')
      div1s = bodys[0].getChildren('div1') #only one body to choose from
      print ""
      for d in div1s:
        attrs = d.getAttributes()
        n = attrs.getFirst('n')
        if n != "Back":
          div2s = d.getChildren('div2')
	  for d2 in div2s:
	    attrs = d.getAttributes()
	    cur_line_number = d2.getLineNumberOnly()
	    get_translation = database.get_translation(cur_line_number, False, False)
	    #print "================="
	    #print get_translation[1]
	    #print "================="
	    if len(get_translation[0]) > 1:
	      tx = key_test.match(get_translation[0])
	      #print tx
	      if tx:
	        get_translation[0] = tx.group()
	    #if cur_line_number == 'S17.02.02':
	    #  print "DEBUG: "+str( type( get_translation[1] ) )
            #  print "DEBUG: "+str( get_translation[1] == '' )
	    #  print "DEBUG: "+str( line_test.match( get_translation[1] ))
            #  print "DEBUG: "+str( get_translation[1] )
	    if empty_line_test.match(get_translation[1]): # == '' or get_translation[1] == None:
	      print get_translation[1]
	      get_translation[0] = '?'
	      get_translation[1] = "We are sorry, this translation has not been entered in the database yet."
	      #print "Key is really: "+str( tx.group() )
	    translation = "<span class=\"ttitle\">[<b style=\'font-size: 14px;\'>Translated from the text of MS "+get_translation[0]+"</b>]</span><br/><br/>"+get_translation[1]
	    translation_table = ''' 
	         <div id="view1" class="viewall" width="javascript:display.width -1px;">
		   <table id="viewall" cellspacing="0" valign="top" height="100%" width="100%">
		     <tr id="header">
		       <td>
		         <table id="versiontitle" width="100%">
			   <tr>
			     <td style="color: white;">&nbsp;<b id="btitle">All versions of Canon '''+cur_line_number+'''</b></td>
			     <td align="right" valign="center">
			       <div class="close" valign="center">
			         <table class="close" style="font-size: 14px; cursor: pointer;" title="Click to close this view." onclick="javascript:window.close()">
				   <tr valign="center"><td><div>&nbsp;X&nbsp;</div></td></tr>
				 </table>
			       </div>
			     </td>
			   </tr>
			 </table>
		       </td>
		     </tr>
		     <tr valign="top" bgcolor="#E5ECFF">
		       <td bgcolor="#E5ECFF" style="min-height: 500px;">
		         <table align="center" valign="top" cellspacing="2px" width="100%" id="content">
	                   <tr valign="top" id="'''+cur_line_number+'''tr" bgcolor="#E5ECFF">
			     <td>
			       <table id="blueborder">
			         <tr bgcolor="#E5ECFF">
				   <td bgcolor="#E5ECFF">
				     <table bgcolor="lightyellow" valign="top" class="version">
				       <tr height="20px">
				         <td id="linetitle">
					   <table id="linenotable" cellspacing="0">
					     <tr>
					       <td>
					         <span id="linenospan"><b id="lineno">&nbsp;'''+cur_line_number+'''&nbsp;</b></span>
					       </td>
					     </tr>
					   </table>
					 </td>
				       </tr>
				       <tr>
				         <td  bgcolor="lightyellow">'''+database.get_line_version(current_key, cur_line_number)+'''</td>
				       </tr>
				     </table>
				   </td>
				 </tr>
			       </table>
			     </td>
			   </tr>
			   <tr id="translationtr">
                             <td>
			       <table id="blueborder">
			         <tr>
				   <td>
				     <table valign="top" class="tversion" border="0">
				       <tr height="20px">
				         <td id="linetitle">
					   <table id="linenotable" cellspacing="0">
					     <tr>
					       <td><span id="linenospan"><b id="lineno">&nbsp;Translation&nbsp;</b></span></td>
					     </tr>
					   </table>
					 </td>
				       </tr>
				       <tr>
				         <td align="left"><div>'''+translation+'''</div></td>
				       </tr>
				     </table>
				   </td>
				 </tr>
			       </table>
			     </td>
			   </tr>
			 </table>
                       </td>
		     </tr>
		     <tr bgcolor="darkblue">
		       <td bgcolor="darkblue">
		         <table id="versiontitle2" width="100%" bgcolor="darkblue">
			   <tr id="header2" style="max-height: 10px;">
			     <td style="color: white;">&nbsp;<b id="btitle">All versions of Canon '''+cur_line_number+'''</b></td>
			     <td align="right" valign="center">
			       <div class="close" valign="center">
			         <table class="close" style="font-size: 14px; cursor: pointer;" title="Click to close this view." onclick="javascript:window.close()">
				   <tr valign="center"><td><div>&nbsp;X&nbsp;</div></td></tr>
				 </table>
			       </div>
			     </td>
			   </tr>
			 </table>
		       </td>
		     </tr>
		   </table>
		 </div>
	    '''
	    return_text = '''
                   <html>
		     <head>
		       <title>Translation of canon '''+cur_line_number+'''</title>
		       <script LANGUAGE="JavaScript">
		         var sw = screen.width*.9;
		         var sh = screen.height*.65;
		         javascript:window.resizeTo(sw,sh);
		         var x = (screen.width-sw)/2;
		         var y = (screen.height-sh)/2;
		         window.moveTo(x,y);
		       </script>
		       <LINK href="main.css" rel="stylesheet" type="text/css"/>
		   '''
            return_text +='''
		     </head>		   		   		   
		     <body bgcolor="lightyellow"><script language="JavaScript" type="text/javascript" src="moving_table.js"></script>
		   '''+translation_table+'''
		       <script language="JavaScript" type="text/javascript" src="wz_tooltip.js"></script>
		     </body>
		   </html>
                  '''
            cur_file = cur_line_number+".html"
	    print "\t > Writing Translation file for canon "+cur_line_number+" to "+FOLDER+"translation_table/"+cur_file
	    files_written += 1
	    file = open(FOLDER+"translation_table/"+cur_file, "w")
	    file.write(return_text)
	    file.close()
  return files_written 
	    #print "\n ---------------" + cur_line_number + "---------------- \n"
	    #print translation
	    #print "\n ---------------------------------------- \n"
	  
#
# THIS GENERATES THE LINE TABLE PAGE WHICH YOU CAN VIEW ALL VERSIONS OF A CANON IN
#
def gen_line_table_pages():
  #Load Database
  lines_written ={}
  files_written = 0
  filename = "data/CORP201.xml"
  _CORP201MS = CORP201MS(filename)
  
  filename = "data/TOEH201.xml"
  _TOEH201MS = TOEH201MS(filename)
  
  filename = "data/CORP265.xml"
  _CORP265MS = CORP265MS(filename)
  
  filename = "data/TOEH265.xml"
  _TOEH256MS = TOEH265MS(filename)
  
  filename = "data/CORP190.xml"
  _CORP190MS = CORP190MS(filename)
  
  filename = "data/TOEI190.xml"
  _TOEI190MS = TOEI190MS(filename)
  
  filename= "data/BX8558.xml"
  _BX8558MS = BX8558MS(filename)
  
  filename = "data/TCTH8558.xml"
  _TCTH8558MS = TCTH8558MS(filename)
  
  filename = "data/LAUD482.xml"
  _LAUD482MS = LAUD482MS(filename)
  
  filename = "data/TOEP482.xml"
  _TOEP482MS = TOEP482MS(filename)

  filename = "data/JUNIUS.xml"
  _JUNIUSMS = JUNIUSMS(filename)

  filename = "data/TSBOC121.xml"
  _TSBOC121MS = TSBOC121MS(filename)
  
  filename = "data/COTTIBA3.xml"
  _COTTIBA3 = COTTIBA3(filename)
  
  filename = "data/TOEH8558.xml"
  _TOEH8558 = TOEH8558MS(filename)
 
  filename = "data/TOEHCTA3.xml"
  _TOEHCTA3 = TOEHCTA3(filename)

  filename = "data/TOEI482.xml"
  _TOEI482 = TOEI482(filename)

  filename = "data/TOEP121.xml"
  _TOEP121 = TOEP121(filename)

  filename = "data/TOEP190.xml"
  _TOEP190 = TOEP190(filename)

  filename = "data/TSBOC190.xml"
  _TSBOC190 = TSBOC190(filename)

  filename = "data/TSBOC482.xml"
  _TSBOC482 = TSBOC482(filename)

  filename = "data/TCTH482.xml"
  _TCTH482 = TCTH482(filename)

  filename = "data/TCTH190.xml"
  _TCTH190 = TCTH190(filename)

  filename = "data/TOEI121.xml"
  _TOEI121 = TOEI121(filename)

  database = manuscript_db(_CORP201MS, _TOEH201MS, _CORP265MS, _TOEH256MS, _CORP190MS, _TOEI190MS, _BX8558MS, _TCTH8558MS, _LAUD482MS, _TOEP482MS, _JUNIUSMS, _TSBOC121MS, _COTTIBA3, _TOEH8558, _TOEHCTA3, _TOEI482, _TOEP121, _TOEP190, _TSBOC190, _TSBOC482, _TCTH482, _TCTH190, _TOEI121) 
  
  for key in  database.manuscripts:
    MS = database.manuscripts[key]['document'].manuscript
    current_key = key
    cur_file =""
    line_in_other_MSS = []
    texts = MS.getChildren("text") 
    bodys = texts[0].getChildren('body')
    div1s = bodys[0].getChildren('div1') #only one body to choose from
    print ""
    for d in div1s:
      attrs = d.getAttributes()
      n = attrs.getFirst('n')
      if n != "Back":
        div2s = d.getChildren('div2')
	for d2 in div2s:
	  line_in_other_MSS = []
	  attrs = d.getAttributes()
	  cur_line_number = d2.getLineNumberOnly()
	  search_line = cur_line_number[1:len(cur_line_number)]	
	  if lines_written.has_key(search_line) != True:
	    lines_written.update({search_line:""})
	    cur_file = search_line+".html"	
	    for key in database.manuscripts: # find line numbers in other docs      
	      if current_key != key: #don't add our current document to search
	        if database.manuscripts[key]['document'].has_line(search_line):		  	  
		  key_found = key+search_line
		  line_in_other_MSS.append(key_found)		   
		  
		  
            if len(line_in_other_MSS) >= 0:	         
	      line_table_checkboxes = '<span style="position: relative; top: 6px;font-size: 12px; background-color: #E5ECFF; padding: 0px;"><form style="color: black;"><span style="margin: 1em; color: black;"><b style="letterspacing: .1em; font-size: 12pt;">View/Hide Canon:</b></span>'
	      line_table_checkboxes += '<span onmouseover="javascript:tbl= new getObj(\''+cur_line_number+'tr\')" style="margin: 1em; color: black;"><input TYPE="checkbox" VALUE="" onclick="javascript:hide_line()" checked>'+cur_line_number+'</span>'
	      for line in line_in_other_MSS:
	        line_table_checkboxes += '<span onmouseover="javascript:tbl= new getObj(\''+line+'tr\')"style="margin: 1em; color: black;"><input TYPE="checkbox" VALUE="" onclick="javascript:hide_line()" checked>'+line+'</span>'
	      line_table_checkboxes += '</form></span>'
	      line_table = '''
                 <div id="view1" class="viewall" width="javascript:display.width -1px;">
		   <table id="viewall" cellspacing="0" valign="top" height="100%" width="100%">
		     <tr id="header">
		       <td>
		         <table id="versiontitle" width="100%">
			   <tr>
			     <td style="color: white;">&nbsp;<b id="btitle">All versions of Canon '''+cur_line_number[1:len(cur_line_number)]+'''</b></td>
			     <td align="right" valign="center">
			       <div class="close" valign="center">
			         <table class="close" style="font-size: 14px; cursor: pointer;" title="Click to close this view." onclick="javascript:window.close()">
				   <tr valign="center"><td><div>&nbsp;X&nbsp;</div></td></tr>
				 </table>
			       </div>
			     </td>
			   </tr>
			 </table>
		       </td>
		     </tr>
		     <tr valign="top" bgcolor="#E5ECFF">
		       <td bgcolor="#E5ECFF" style="min-height: 500px;">
		         <table align="center" valign="top" cellspacing="2px" width="100%" id="content">
		           <tr bgcolor="#E5ECFF">
			     <td bgcolor="#E5ECFF">
			       <table style="background-color: darkblue; padding: 1px; width: 100%;">
			        <tr bgcolor="#E5ECFF">
				  <td bgcolor="#E5ECFF">'''+line_table_checkboxes+'''</td>
				</tr>
			       </table>
			     </td>
			   </tr>
			   <tr valign="top" id="'''+cur_line_number+'''tr" bgcolor="#E5ECFF">
			     <td>
			       <table id="blueborder">
			         <tr bgcolor="#E5ECFF">
				   <td bgcolor="#E5ECFF">
				     <table bgcolor="lightyellow" valign="top" class="version">
				       <tr height="20px">
				         <td id="linetitle">
					   <table id="linenotable" cellspacing="0">
					     <tr>
					       <td>
					         <span id="linenospan"><b id="lineno">&nbsp;'''+cur_line_number+'''&nbsp;</b></span>
					       </td>
					     </tr>
					   </table>
					 </td>
				       </tr>
				       <tr>
				         <td  bgcolor="lightyellow">'''+database.get_line_version(current_key, cur_line_number)+'''</td>
				       </tr>
				     </table>
				   </td>
				 </tr>
			       </table>
			     </td>
			   </tr>'''
  #lines_entered += 1
              for line in line_in_other_MSS:
                line_insert = database.get_line_version(line[0], line)
                line_table += '''    <tr id="'''+line+'''tr">
                             <td>
			       <table id="blueborder">
			         <tr>
				   <td>
				     <table valign="top" class="version">
				       <tr height="20px">
				         <td id="linetitle">
					   <table id="linenotable" cellspacing="0">
					     <tr>
					       <td><span id="linenospan"><b id="lineno">&nbsp;'''+line+'''&nbsp;</b></span></td>
					     </tr>
					   </table>
					 </td>
				       </tr>
				       <tr>
				         <td>'''+line_insert+'''</td>
				       </tr>
				     </table>
				   </td>
				 </tr>
			       </table>
			     </td>
			   </tr>'''
      
              line_table += '''    </table>
                       </td>
		     </tr>
		     <tr bgcolor="darkblue">
		       <td bgcolor="darkblue">
		         <table id="versiontitle2" width="100%" bgcolor="darkblue">
			   <tr id="header2" style="max-height: 10px;">
			     <td style="color: white;">&nbsp;<b id="btitle">All versions of Canon '''+cur_line_number[1:len(cur_line_number)]+'''</b></td>
			     <td align="right" valign="center">
			       <div class="close" valign="center">
			         <table class="close" style="font-size: 14px; cursor: pointer;" title="Click to close this view." onclick="javascript:window.close()">
				   <tr valign="center"><td><div>&nbsp;X&nbsp;</div></td></tr>
				 </table>
			       </div>
			     </td>
			   </tr>
			 </table>
		       </td>
		     </tr>
		   </table>
		 </div>'''
              return_text = '''
                   <html>
		     <head>
		       <title>All versions of canon '''+cur_line_number[1:len(cur_line_number)]+'''</title>
		       <script LANGUAGE="JavaScript">
		         var sw = screen.width*.9;
		         var sh = screen.height*.65;
		         javascript:window.resizeTo(sw,sh);
		         var x = (screen.width-sw)/2;
		         var y = (screen.height-sh)/2;
		         window.moveTo(x,y);
		       </script>
		       <LINK href="main.css" rel="stylesheet" type="text/css"/>
		   '''
              #for key in database.styles:
              #  return_text += database.styles[key]["single"]
              return_text +='''
		     </head>		   		   		   
		     <body bgcolor="lightyellow"><script language="JavaScript" type="text/javascript" src="moving_table.js"></script>
		   '''+line_table+'''
		       <script language="JavaScript" type="text/javascript" src="wz_tooltip.js"></script>
		     </body>
		   </html>
                  '''
	      print "\t > Writing line table for canon line#"+search_line+" to "+FOLDER+"line_table/"+cur_file
	      files_written += 1
	      file = open(FOLDER+"line_table/"+cur_file, "w")
	      file.write(return_text)
	      file.close()
	    
  return files_written

def gen_main_pages():
  #Load Database
  filename = "data/CORP201.xml"
  _CORP201MS = CORP201MS(filename)
  
  filename = "data/TOEH201.xml"
  _TOEH201MS = TOEH201MS(filename)
  
  filename = "data/CORP265.xml"
  _CORP265MS = CORP265MS(filename)
  
  filename = "data/TOEH265.xml"
  _TOEH256MS = TOEH265MS(filename)
  
  filename = "data/CORP190.xml"
  _CORP190MS = CORP190MS(filename)
  
  filename = "data/TOEI190.xml"
  _TOEI190MS = TOEI190MS(filename)
  
  filename= "data/BX8558.xml"
  _BX8558MS = BX8558MS(filename)
  
  filename = "data/TCTH8558.xml"
  _TCTH8558MS = TCTH8558MS(filename)
  
  filename = "data/LAUD482.xml"
  _LAUD482MS = LAUD482MS(filename)
  
  filename = "data/TOEP482.xml"
  _TOEP482MS = TOEP482MS(filename)
  
  filename = "data/JUNIUS.xml"
  _JUNIUSMS = JUNIUSMS(filename)

  filename = "data/TSBOC121.xml"
  _TSBOC121MS = TSBOC121MS(filename)
  
  filename = "data/COTTIBA3.xml"
  _COTTIBA3 = COTTIBA3(filename)
 
  filename = "data/TOEH8558.xml"
  _TOEH8558 = TOEH8558MS(filename)

  filename = "data/TOEHCTA3.xml"
  _TOEHCTA3 = TOEHCTA3(filename) 
  
  filename = "data/TOEI482.xml"
  _TOEI482 = TOEI482(filename)

  filename = "data/TOEP121.xml"
  _TOEP121 = TOEP121(filename)

  filename = "data/TOEP190.xml"
  _TOEP190 = TOEP190(filename)

  filename = "data/TSBOC190.xml"
  _TSBOC190 = TSBOC190(filename)

  filename = "data/TSBOC482.xml"
  _TSBOC482 = TSBOC482(filename)

  filename = "data/TCTH482.xml"
  _TCTH482 = TCTH482(filename)

  filename = "data/TCTH190.xml"
  _TCTH190 = TCTH190(filename)

  filename = "data/TOEI121.xml"
  _TOEI121 = TOEI121(filename)

  database = manuscript_db(_CORP201MS, _TOEH201MS, _CORP265MS, _TOEH256MS, _CORP190MS, _TOEI190MS, _BX8558MS, _TCTH8558MS, _LAUD482MS, _TOEP482MS, _JUNIUSMS, _TSBOC121MS, _COTTIBA3, _TOEH8558, _TOEHCTA3, _TOEI482, _TOEP121, _TOEP190, _TSBOC190, _TSBOC482, _TCTH482, _TCTH190, _TOEI121)
  
  files_written = 0
  print ""
  for key in database.manuscripts:
    cur_file = FILENAMES[key]
    CURFILE = FILENAMES[key] #global
    print "SET CURFILE TO: "+CURFILE
    style='''
        <style>
	div#h1
{
position: absolute;
top: 0;
left: 0;
width: 100%;
min-width: 1200px;
height: 2em;
background-color: #E5ECFF; 
color: #626C9B; 
font-family: arial, sans serif; 
font-weight: bold;
font-size: 23px; 
border-bottom: double 3px #626C9B; 
border-top: 2px black groove;
padding: 0;
}
	div#h1 span#edited_by
{
  position: absolute; 
  right: 0;
  font-size: 18pt;
  margin-right: 50px;
  bottom: 4px;
}
	div#h1 span a{text-decoration: none; color: #626C9B;}
div#h1 span{
position: absolute; 
margin-left: .75em;
bottom: 4px;
}
	a#homelink
	{
	text-decoration: none;
	color: #626C9B;
	}
	div#MS_container
	{
	 position: relative;	 
	 top: 4em;	 
	 background-color: lightyellow;
	 width: 95%;
	 min-width: 950px;
	 border-right: double 3px black;
	 border-bottom: double 3px black;
	 border-top: solid 1px black;
	 border-left: solid 1px black;
	}
	h2{
	display: inline;
	padding-left: 1em;
	width: 100%;
	font-size: 16pt;
	font-family: arial, sans serif;
	color: ivory; background-color: 00ccff;
	}
	div#header
	{
	width: 100%;
	background-color: #00ccff;
	text-align: right;
	letter-spacing: .10em;
	border-bottom: solid 1px black;
	}
	table#page
	{
	border: 0;
	border-style: groove;
	}
	'''+database.get_one_MS_style()+'''
	</style>
	'''
    text = '<html>'
    text += '<head>'
    text += style
    text += '<scriptlanguage="JavaScript" src="new_window.js"></script>'
    text += '''
          <script language="JavaScript">
	    <!-- 
	    function open_new_window(url)
	    { 
	    new_window = window.open(url,'Viewall','toolbar=no,scrollbars=yes,menubar=no,resizable=yes,dependent=no,status=yes,width=180,height=60,left=100,top=100')
	    }
	    -->
	    </script>
            '''
    text += '</head>'
    text += '<body bgcolor="#626C9B">'
    text += '<div id="h1"><span><a id="homelink" title="Click here to go back to the main page." href="'+HOMEPAGE+'">The Anglo-Saxon Penitentials: <div style="display: inline; font-size: 18pt;">A cultural database</div></a></span><span id="edited_by"><a href="http://www.luc.edu/faculty/afrantz/" title="This will open the home page of Allen J. Frantzen in a new window." target="_blank">edited by Allen J. Frantzen<a/></span></div>'
    text += '<center><div id="MS_container"><div id="header"><h2 style="margin-right: 1.5em;">'+database.get_MS_name(key)+'</h2></div>'
    text += '<center><table width="98%" id="page" style="min-width: 900px;"><tr><td><table width="75%" cellpadding="5" border="0" align="center"><tr><td><table border="0" cellpadding="0" align="center"><tr><td>'

    text += database.get_one_MS(key)
    text += "</td></tr></table></td></tr></table></td></tr></table></center>"
    text += "</div></center>"
    text += '<div style="height: 280px;">&nbsp</div>'
    text += '<script language="JavaScript" type="text/javascript" src="moving_table.js"></script>'
    text += '<script language="JavaScript" type="text/javascript" src="wz_tooltip.js"></script>'
    text += "</body>"
    text += "</html>"
    print "\t > Writing manuscript "+key+" "+FOLDER+cur_file
    files_written += 1
    file = open(FOLDER+cur_file, "w")
    file.write(text)
    file.close()
     
  return files_written
  

def gen_all_MS_paged():
  #Load Database
  global CURRENT_FILE
  filename = "data/CORP201.xml"
  _CORP201MS = CORP201MS(filename)
  
  filename = "data/TOEH201.xml"
  _TOEH201MS = TOEH201MS(filename)
  
  filename = "data/CORP265.xml"
  _CORP265MS = CORP265MS(filename)
  
  filename = "data/TOEH265.xml"
  _TOEH256MS = TOEH265MS(filename)
  
  filename = "data/CORP190.xml"
  _CORP190MS = CORP190MS(filename)
  
  filename = "data/TOEI190.xml"
  _TOEI190MS = TOEI190MS(filename)
  
  filename= "data/BX8558.xml"
  _BX8558MS = BX8558MS(filename)
  
  filename = "data/TCTH8558.xml"
  _TCTH8558MS = TCTH8558MS(filename)
  
  filename = "data/LAUD482.xml"
  _LAUD482MS = LAUD482MS(filename)
  
  filename = "data/TOEP482.xml"
  _TOEP482MS = TOEP482MS(filename)
  
  filename = "data/JUNIUS.xml"
  _JUNIUSMS = JUNIUSMS(filename)

  filename = "data/TSBOC121.xml"
  _TSBOC121MS = TSBOC121MS(filename)

  filename = "data/COTTIBA3.xml"
  _COTTIBA3 = COTTIBA3(filename)
  
  filename = "data/TOEH8558.xml"
  _TOEH8558 = TOEH8558MS(filename)

  filename = "data/TOEHCTA3.xml"
  _TOEHCTA3 = TOEHCTA3(filename)

  filename = "data/TOEI482.xml"
  _TOEI482 = TOEI482(filename)

  filename = "data/TOEP121.xml"
  _TOEP121 = TOEP121(filename)

  filename = "data/TOEP190.xml"
  _TOEP190 = TOEP190(filename)

  filename = "data/TSBOC190.xml"
  _TSBOC190 = TSBOC190(filename)

  filename = "data/TSBOC482.xml"
  _TSBOC482 = TSBOC482(filename)

  filename = "data/TCTH482.xml"
  _TCTH482 = TCTH482(filename)

  filename = "data/TCTH190.xml"
  _TCTH190 = TCTH190(filename)
 
  filename = "data/TOEI121.xml"
  _TOEI121 = TOEI121(filename)

  database = manuscript_db(_CORP201MS, _TOEH201MS, _CORP265MS, _TOEH256MS, _CORP190MS, _TOEI190MS, _BX8558MS, _TCTH8558MS, _LAUD482MS, _TOEP482MS, _JUNIUSMS, _TSBOC121MS, _COTTIBA3, _TOEH8558, _TOEHCTA3, _TOEI482, _TOEP121, _TOEP190, _TSBOC190, _TSBOC482, _TCTH482, _TCTH190, _TOEI121)

  #database = manuscript_db(_CORP201MS,_TOEH201MS,_CORP265MS,_TOEH256MS,_CORP190MS,_TOEI190MS,_BX8558MS,_TCTH8558MS,_LAUD482MS,_TOEP482MS,_JUNIUSMS,_TSBOC121MS, _COTTIBA3 )

#
  # build line page data abse...this will simultaneously build the page map
  #
  TRANS_LPDB.build_lpdb(database)
  MS_LPDB.build_lpdb(database)
  
  #for page in MS_PG_MAP.database[ key ]:
  CURRENT_FILE.set_type('manuscript')
  CURRENT_FILE.turn_on_debug()
  #CURRENT_FILE.add_text( HTML_PAGE_OPEN )

  database.get_all_MS_paged()
  
  print "Manuscript files written: "+str(CURRENT_FILE.get_files_written())


def gen_one_TRANSLATION_paged(key=None):
  #print "THIS IS STILL BEING DEVELOPED AND DOES NOT WORK AT THIS POINT AND TIME"
  #print "translation called with "+str( key )
  #return ''
  global CURRENT_MS_KEY, MS_LPDB, FILENAMES, MS_PG_MAP, CURRENT_FILE
  #Load Database
  filename = "data/CORP201.xml"
  _CORP201MS = CORP201MS(filename)
  
  filename = "data/TOEH201.xml"
  _TOEH201MS = TOEH201MS(filename)
  
  filename = "data/CORP265.xml"
  _CORP265MS = CORP265MS(filename)
  
  filename = "data/TOEH265.xml"
  _TOEH256MS = TOEH265MS(filename)
  
  filename = "data/CORP190.xml"
  _CORP190MS = CORP190MS(filename)
  
  filename = "data/TOEI190.xml"
  _TOEI190MS = TOEI190MS(filename)
  
  filename= "data/BX8558.xml"
  _BX8558MS = BX8558MS(filename)
  
  filename = "data/TCTH8558.xml"
  _TCTH8558MS = TCTH8558MS(filename)
  
  filename = "data/LAUD482.xml"
  _LAUD482MS = LAUD482MS(filename)
  
  filename = "data/TOEP482.xml"
  _TOEP482MS = TOEP482MS(filename)
  
  filename = "data/JUNIUS.xml"
  _JUNIUSMS = JUNIUSMS(filename)

  filename = "data/TSBOC121.xml"
  _TSBOC121MS = TSBOC121MS(filename)

  filename = "data/COTTIBA3.xml"
  _COTTIBA3 = COTTIBA3(filename)
  
  filename = "data/TOEH8558.xml"
  _TOEH8558 = TOEH8558MS(filename)
  
  filename = "data/TOEHCTA3.xml"
  _TOEHCTA3 = TOEHCTA3(filename)
  
  filename = "data/TOEI482.xml"
  _TOEI482 = TOEI482(filename)

  filename = "data/TOEP121.xml"
  _TOEP121 = TOEP121(filename)

  filename = "data/TOEP190.xml"
  _TOEP190 = TOEP190(filename)

  filename = "data/TSBOC190.xml"
  _TSBOC190 = TSBOC190(filename)

  filename = "data/TSBOC482.xml"
  _TSBOC482 = TSBOC482(filename)

  filename = "data/TCTH482.xml"
  _TCTH482 = TCTH482(filename)

  filename = "data/TCTH190.xml"
  _TCTH190 = TCTH190(filename)

  filename = "data/TOEI121.xml"
  _TOEI121 = TOEI121(filename)

  database = manuscript_db(_CORP201MS, _TOEH201MS, _CORP265MS, _TOEH256MS, _CORP190MS, _TOEI190MS, _BX8558MS, _TCTH8558MS, _LAUD482MS, _TOEP482MS, _JUNIUSMS, _TSBOC121MS, _COTTIBA3, _TOEH8558, _TOEHCTA3, _TOEI482, _TOEP121, _TOEP190, _TSBOC190, _TSBOC482, _TCTH482, _TCTH190, _TOEI121)
  
  #
  # build line page data abse...this will simultaneously build the page map
  #
  
  TRANS_LPDB.build_lpdb(database)
  MS_LPDB.build_lpdb(database)
  #for page in MS_PG_MAP.database[ key ]:
  CURRENT_FILE.set_type('translation')
  CURRENT_FILE.turn_on_debug()
  #CURRENT_FILE.add_text( HTML_PAGE_OPEN )
  
  print "Working on translation..."
  #return ''
  #print "TRANS MAP DEBUG: "+str( TRANS_LPDB.get_key_of_trans_map( "S44.18.02" ) )
  if key != None:
    database.get_translation_paged(key)
  else:
    for key in database.translations.keys():
      database.get_translation_paged(key)
    
def gen_one_MS_paged(key):
  global CURRENT_MS_KEY, MS_LPDB, FILENAMES, MS_PG_MAP, CURRENT_FILE
  #Load Database
  filename = "data/CORP201.xml"
  _CORP201MS = CORP201MS(filename)
  
  filename = "data/TOEH201.xml"
  _TOEH201MS = TOEH201MS(filename)
  
  filename = "data/CORP265.xml"
  _CORP265MS = CORP265MS(filename)
  
  filename = "data/TOEH265.xml"
  _TOEH256MS = TOEH265MS(filename)
  
  filename = "data/CORP190.xml"
  _CORP190MS = CORP190MS(filename)
  
  filename = "data/TOEI190.xml"
  _TOEI190MS = TOEI190MS(filename)
  
  filename= "data/BX8558.xml"
  _BX8558MS = BX8558MS(filename)
  
  filename = "data/TCTH8558.xml"
  _TCTH8558MS = TCTH8558MS(filename)
  
  filename = "data/LAUD482.xml"
  _LAUD482MS = LAUD482MS(filename)
  
  filename = "data/TOEP482.xml"
  _TOEP482MS = TOEP482MS(filename)
  
  filename = "data/JUNIUS.xml"
  _JUNIUSMS = JUNIUSMS(filename)

  filename = "data/TSBOC121.xml"
  _TSBOC121MS = TSBOC121MS(filename)

  filename = "data/COTTIBA3.xml"
  _COTTIBA3 = COTTIBA3(filename)
  
  filename = "data/TOEH8558.xml"
  _TOEH8558 = TOEH8558MS(filename)
  
  filename = "data/TOEHCTA3.xml"
  _TOEHCTA3 = TOEHCTA3(filename)
  
  filename = "data/TOEI482.xml"
  _TOEI482 = TOEI482(filename)

  filename = "data/TOEP121.xml"
  _TOEP121 = TOEP121(filename)

  filename = "data/TOEP190.xml"
  _TOEP190 = TOEP190(filename)

  filename = "data/TSBOC190.xml"
  _TSBOC190 = TSBOC190(filename)

  filename = "data/TSBOC482.xml"
  _TSBOC482 = TSBOC482(filename)

  filename = "data/TCTH482.xml"
  _TCTH482 = TCTH482(filename)

  filename = "data/TCTH190.xml"
  _TCTH190 = TCTH190(filename)

  filename = "data/TOEI121.xml"
  _TOEI121 = TOEI121(filename)

  database = manuscript_db(_CORP201MS, _TOEH201MS, _CORP265MS, _TOEH256MS, _CORP190MS, _TOEI190MS, _BX8558MS, _TCTH8558MS, _LAUD482MS, _TOEP482MS, _JUNIUSMS, _TSBOC121MS, _COTTIBA3, _TOEH8558, _TOEHCTA3, _TOEI482, _TOEP121, _TOEP190, _TSBOC190, _TSBOC482, _TCTH482, _TCTH190, _TOEI121) 
  #
  # build line page data abse...this will simultaneously build the page map
  #
  TRANS_LPDB.build_lpdb(database)
  MS_LPDB.build_lpdb(database)
  
  print "GEN ON START DEBUG: "+str(MS_LPDB.get_page("Y07.04.01"))
  
  CURRENT_FILE.set_type('manuscript')
  #for page in MS_PG_MAP.database[ key ]:
  CURRENT_FILE.turn_on_debug()
  #CURRENT_FILE.add_text( HTML_PAGE_OPEN )

  
  database.get_one_MS_paged(key)
  #print "Files written: "+str( CURRENT_FILE.get_files_written() )
   


#
# gen_one_MS renders an entire document to one large HTML manuscript
# this is a version 1 function, now obsolete but functionality was left
# DEPRECIATED DO NOT USE!!
#
def gen_one_MS(key):
  #Load Database
  filename = "data/CORP201.xml"
  _CORP201MS = CORP201MS(filename)
  
  filename = "data/TOEH201.xml"
  _TOEH201MS = TOEH201MS(filename)
  
  filename = "data/CORP265.xml"
  _CORP265MS = CORP265MS(filename)
 
  filename = "data/TOEH265.xml"
  _TOEH256MS = TOEH265MS(filename)
  
  filename = "data/CORP190.xml"
  _CORP190MS = CORP190MS(filename)
  
  filename = "data/TOEI190.xml"
  _TOEI190MS = TOEI190MS(filename)
  
  filename= "data/BX8558.xml"
  _BX8558MS = BX8558MS(filename)
  
  filename = "data/TCTH8558.xml"
  _TCTH8558MS = TCTH8558MS(filename)
  
  filename = "data/LAUD482.xml"
  _LAUD482MS = LAUD482MS(filename)
  
  filename = "data/TOEP482.xml"
  _TOEP482MS = TOEP482MS(filename)
  
  filename = "data/JUNIUS.xml"
  _JUNIUSMS = JUNIUSMS(filename)

  filename = "data/TSBOC121.xml"
  _TSBOC121MS = TSBOC121MS(filename)
  
  filename = "data/COTTIBA3.xml"
  _COTTIBA3 = COTTIBA3(filename)
  
  filename = "data/TOEH8558.xml"
  _TOEH8558 = TOEH8558MS(filename)

  filename = "data/TOEHCTA3.xml"
  _TOEHCTA3 = TOEHCTA3(filename) 
 
  filename = "data/TOEI482.xml"
  _TOEI482 = TOEI482(filename)

  filename = "data/TOEP121.xml"
  _TOEP121 = TOEP121(filename)

  filename = "data/TOEP190.xml"
  _TOEP190 = TOEP190(filename)

  filename = "data/TSBOC190.xml"
  _TSBOC190 = TSBOC190(filename)

  filename = "data/TSBOC482.xml"
  _TSBOC482 = TSBOC482(filename)

  filename = "data/TCTH482.xml"
  _TCTH482 = TCTH482(filename)

  filename = "data/TCTH190.xml"
  _TCTH190 = TCTH190(filename)
  
  filename = "data/TOEI121.xml"
  _TOEI121 = TOEI121(filename)

  database = manuscript_db(_CORP201MS, _TOEH201MS, _CORP265MS, _TOEH256MS, _CORP190MS, _TOEI190MS, _BX8558MS, _TCTH8558MS, _LAUD482MS, _TOEP482MS, _JUNIUSMS, _TSBOC121MS, _COTTIBA3, _TOEH8558, _TOEHCTA3, _TOEI482, _TOEP121, _TOEP190, _TSBOC190, _TSBOC482, _TCTH482, _TCTH190, _TOEI121) 
  files_written = 0
  print ""
  #for key in database.manuscripts:
  cur_file = FILENAMES[key]
  CURFILE = FILENAMES[key] #global
  print "SET CURFILE TO: "+CURFILE
  style='''
        <style>
	div#h1
{
position: absolute;
top: 0;
left: 0;
width: 100%;
min-width: 1200px;
height: 2em;
background-color: #E5ECFF; 
color: #626C9B; 
font-family: arial, sans serif; 
font-weight: bold;
font-size: 23px; 
border-bottom: double 3px #626C9B; 
border-top: 2px black groove;
padding: 0;
}
	div#h1 span#edited_by
{
  position: absolute; 
  right: 0;
  font-size: 18pt;
  margin-right: 50px;
  bottom: 4px;
}
	div#h1 span a{text-decoration: none; color: #626C9B;}
div#h1 span{
position: absolute; 
margin-left: .75em;
bottom: 4px;
}
	a#homelink
	{
	text-decoration: none;
	color: #626C9B;
	}
	div#MS_container
	{
	 position: relative;	 
	 top: 4em;	 
	 background-color: lightyellow;
	 width: 95%;
	 min-width: 950px;
	 border-right: double 3px black;
	 border-bottom: double 3px black;
	 border-top: solid 1px black;
	 border-left: solid 1px black;
	}
	h2{
	display: inline;
	padding-left: 1em;
	width: 100%;
	font-size: 16pt;
	font-family: arial, sans serif;
	color: ivory; background-color: 00ccff;
	}
	div#header
	{
	width: 100%;
	background-color: #00ccff;
	text-align: right;
	letter-spacing: .10em;
	border-bottom: solid 1px black;
	}
	table#page
	{
	border: 0;
	border-style: groove;
	}
	'''+database.get_one_MS_style()+'''
	</style>
	'''
  text = '<html>'
  text += '<head>'
  text += style
  text += '<script language="JavaScript" src="new_window.js"></script>'
  text += '''
          <script language="JavaScript">
	    <!-- 
	    function open_new_window(url)
	    { 
	    new_window = window.open(url,'Viewall','toolbar=no,scrollbars=yes,menubar=no,resizable=yes,dependent=no,status=yes,width=180,height=60,left=100,top=100')
	    }
	    -->
	    </script>
            '''
  text += '</head>'
  text += '<body bgcolor="#626C9B">'
  text += '<div id="h1"><span><a id="homelink" title="Click here to go back to the main page." href="'+HOMEPAGE+'">The Anglo-Saxon Penitentials: <div style="display: inline; font-size: 18pt;">A cultural database</div></a></span><span id="edited_by"><a href="http://www.luc.edu/faculty/afrantz/" title="This will open the home page of Allen J. Frantzen in a new window." target="_blank">edited by Allen J. Frantzen<a/></span></div>'
  text += '<center><div id="MS_container"><div id="header"><h2 style="margin-right: 1.5em;">'+database.get_MS_name(key)+'</h2></div>'
  text += '<center><table width="98%" id="page" style="min-width: 900px;"><tr><td><table width="75%" cellpadding="5" border="0" align="center"><tr><td><table border="0" cellpadding="0" align="center"><tr><td>'

  text += database.get_one_MS(key)
  text += "</td></tr></table></td></tr></table></td></tr></table></center>"
  text += "</div></center>"
  text += '<div style="height: 280px;">&nbsp</div>'
  text += '<script language="JavaScript" type="text/javascript" src="moving_table.js"></script>'
  text += '<script language="JavaScript" type="text/javascript" src="wz_tooltip.js"></script>'
  text += "</body>"
  text += "</html>"
  print "\t > Writing manuscript "+key+" "+FOLDER+cur_file
  files_written += 1
  file = open(FOLDER+cur_file, "w")
  file.write(text)
  file.close()
  return files_written
  
def copy_site_files():
  global FOLDER
  to_locations = [FOLDER, FOLDER+'line_table/', FOLDER+'translation_table/']
  files_written =0
  print "Copying script files and image files..."
  for sfile in SITEFILES:
    cur_file = sfile
    from_file = open("sitefiles/"+str(sfile), "r")    
    ff_data = from_file.read()
    for tf in to_locations:
      print "\tCopying "+cur_file+" to "+tf+sfile
      to_file = open(tf+sfile, "w")
      to_file.write(ff_data)
      to_file.close()
      files_written += 1
  print "Copying main HTML files..." 
  for mfile in MAINFILES:
    cur_file = mfile
    from_file = open("mainfiles/"+str(mfile), "r")
    ff_data = from_file.read()
    # Adds the header and menu code from config.xml, so the menu is consistent across all pages -cg
    if mfile.endswith('.html'):
      ff_data = ff_data.replace('$STATIC_HEADER_TOP', configMap['STATIC_HEADER_TOP'])
      ff_data = ff_data.replace('$STATIC_HEADER_BOTTOM', configMap['STATIC_HEADER_BOTTOM'])
      ff_data = ff_data.replace('$MENU', configMap['MSMENU'])
      ff_data = ff_data.replace('$STATIC_FOOTER', configMap['STATIC_FOOTER'])    
    print "\tCopying "+cur_file+" to "+FOLDER+mfile
    to_file = open(FOLDER+mfile, "w")
    to_file.write(ff_data)
    to_file.close()
    files_written += 1
  return files_written   
    

#
# build a database of page numbers and canon numbers on those pages
# not an object because bing global make it a bit difficult....and I don't want to move it out of this file 

def get_pg_and_line_no(translation = False):
  global CURRENT_MS_KEY, MS_LPDB, FILENAMES, MS_PG_MAP, FILENAMES
  #Load Database
  filename = "data/CORP201.xml"
  _CORP201MS = CORP201MS(filename)
  
  filename = "data/TOEH201.xml"
  _TOEH201MS = TOEH201MS(filename)
  
  filename = "data/CORP265.xml"
  _CORP265MS = CORP265MS(filename)
  
  filename = "data/TOEH265.xml"
  _TOEH256MS = TOEH265MS(filename)
  
  filename = "data/CORP190.xml"
  _CORP190MS = CORP190MS(filename)
  
  filename = "data/TOEI190.xml"
  _TOEI190MS = TOEI190MS(filename)
  
  filename= "data/BX8558.xml"
  _BX8558MS = BX8558MS(filename)
  
  filename = "data/TCTH8558.xml"
  _TCTH8558MS = TCTH8558MS(filename)
  
  filename = "data/LAUD482.xml"
  _LAUD482MS = LAUD482MS(filename)
  
  filename = "data/TOEP482.xml"
  _TOEP482MS = TOEP482MS(filename)
  
  filename = "data/JUNIUS.xml"
  _JUNIUSMS = JUNIUSMS(filename)

  filename = "data/TSBOC121.xml"
  _TSBOC121MS = TSBOC121MS(filename)
  
  filename = "data/COTTIBA3.xml"
  _COTTIBA3 = COTTIBA3(filename)

  filename = "data/TOEH8558.xml"
  _TOEH8558 = TOEH8558MS(filename)

  filename = "data/TOEHCTA3.xml"
  _TOEHCTA3 = TOEHCTA3(filename)
  
  filename = "data/TOEI482.xml"
  _TOEI482 = TOEI482(filename)

  filename = "data/TOEP121.xml"
  _TOEP121 = TOEP121(filename)

  filename = "data/TOEP190.xml"
  _TOEP190 = TOEP190(filename)

  filename = "data/TSBOC190.xml"
  _TSBOC190 = TSBOC190(filename)

  filename = "data/TSBOC482.xml"
  _TSBOC482 = TSBOC482(filename)

  filename = "data/TCTH482.xml"
  _TCTH482 = TCTH482(filename)

  filename = "data/TCTH190.xml"
  _TCTH190 = TCTH190(filename)

  filename = "data/TOEI121.xml"
  _TOEI121 = TOEI121(filename)

  database = manuscript_db(_CORP201MS, _TOEH201MS, _CORP265MS, _TOEH256MS, _CORP190MS, _TOEI190MS, _BX8558MS, _TCTH8558MS, _LAUD482MS, _TOEP482MS, _JUNIUSMS, _TSBOC121MS, _COTTIBA3, _TOEH8558, _TOEHCTA3, _TOEI482, _TOEP121, _TOEP190, _TSBOC190, _TSBOC482, _TCTH482, _TCTH190, _TOEI121)
  #
  # This will have to be done for each manuscript...before rendering...
  #
  #CURRENT_MS_KEY = 'D'
  if translation:
    print "** PRINTING TRANSLATION LPDB **"
    TRANS_LPDB.build_lpdb(database)
    TRANS_LPDB.print_lpdb()
    print "Printing page map"
    TRANS_PG_MAP.print_page_map()
    key = 'S'
    print "MS "+key+" Tests" 
  
    fp = TRANS_PG_MAP.get_first_page(key)
    lp = TRANS_PG_MAP.get_last_page(key)

    print "first page: "+ fp
    print "next page: "+ TRANS_PG_MAP.get_next_page(key, fp)
    print "last page: "+ lp
    print "next to last page: "+ TRANS_PG_MAP.get_previous_page(key, lp)
  
  else:
    print "** PRINTING MANUSCRIOT LPDB **"
    TRANS_LPDB.build_lpdb(database)
    MS_LPDB.build_lpdb(database)
    MS_LPDB.print_lpdb()
    MS_PG_MAP.print_page_map()
    key = 'S'
    print "MS "+key+" Tests" 
  
    fp = MS_PG_MAP.get_first_page(key)
    lp = MS_PG_MAP.get_last_page(key)

    print "first page: "+ fp
    print "next page: "+ MS_PG_MAP.get_next_page(key, fp)
    print "last page: "+ lp
    print "next to last page: "+ MS_PG_MAP.get_previous_page(key, lp)
  """
  for x in ['D','C']:
    CURRENT_MS_KEY = x 
    MS = database.manuscripts[ CURRENT_MS_KEY ]['document'].manuscript
    #header = MS.getChildren("teiHeader")
    texts = MS.getChildren("text")
    temp =[]
    body = texts[0].getChildren('body')
    line_db = body[0].get_lines_per_page()
  """
  
  

  """
  print "-- MS Key --|--  line no  -- | -- page no --"
  print "````````````````````````````````````````````"
  for x in['D','C']:
    for item in MS_LPDB[x]:
      print "--    "+ x +"   --|-- "+ str( item[0] ) +" -- | --   "+ str( item[1] )+ "   -- "
  """

#
# PRINT COMMANDS TO USER
#
  
def print_help():
   print '''
              usage: python translator.py --[command] 

              COMMANDS:
	           --all	tanslates all manuscripts in the database to folder '''+FOLDER+'''
		        	and copies all non-generated site files to folder '''+FOLDER+'''
					
		   --msp <manuscript letter>      
		   	     translates a specific manuscript, broken in to pages, to folder '''+FOLDER+'''
		   
                   --ms (DEPRECIDATED!) <manuscript letter>
		             translates an entire manuscript into a single file.  This was the old
			     version of this translation function and you are advised to use the 
			     new '--msp' command.  THERE IS NO GUARANTEE THIS WILL WORK AND WILL 
			     PROBABLY BE REMOVED IN THE FUTURE.

		   --lpdb
		             prints out all line to page mapping for every manuscript and also
			     prints out all page to page navigation mapping.  This only prints
			     to the screen you are reading and is for viewing informaton.  This
			     function does nothing in generating the site files itself but only 
			     shows the unlying structure of the canon(line as laypeople/programers call it) 
			     to page database setup.
		   
		   --main    translates only manuscripts, does not generate the canon comparison table or translation table
		   	     files, or copy any static files.
		   
		   --ct      translates only the canon table comparison files (no full manuscripts are tranlated to html here).

		   --tt	     translates only the canon + translation files (no full manuscripts are tranlated to html here).
		   
		   --copy    copies all non-generated site files to folder '''+FOLDER+'''

		   --lm	     list all non-generated html files for the OE Project.

		   --setup   Tells you how to setup the directory structure.  Some day it will actually set up the folder 
		   	     structure for you...some day :-(
	      
            '''
def print_setup():
  print """
	To setup the directory, go to the folder which will be written to.
        The folder structure should be as follows:

	"""+str(FOLDER)+ """
	|		
	|-----pics/
	|		
	|
	|-----translation_table/
	|     	|
	|     	|-----pics/
	|
	|
	|-----line_table/
		|
		|-----pics/

	1) Under the path """+str(FOLDER)+""" make the directories 'pics', 'translation_table', 
	   and 'line_table'.
	2) Under folder """+str(FOLDER)+"""translation_table/ make a directory 'pics'.
	3) Under the folder """+str(FOLDER)+"""line_table/ folder make a directory 'pics'.
	4) You have now completed the setup.  You can run ./translation.py --copy and 
	   it should work properly.
	
	"""  
def print_warning(show_static = False):
  if not show_static:
    print '''
************************************************************************************************************
	  NOTE: 
	     SINCE THE TRANSLATOR DID NOT BUILD THE ENTIRE SITE,
	     RUN 'python translator.py --copy' OR RUN
	     THIS PROGRAM AS 'python translatop.py --staticinfo' 
	     TO SEE A LIST OF ALL THE STATIC FILES AND WHERE TO 
	     COPY THEM.
************************************************************************************************************
'''
  else:
    print '''
************************************************************************************************************
	     MAKE SURE YOU COPY THE FOLLOWNG FILES
	     TO THE FOLLOWING DIRECTORIES...
	============================================================================================= 
		FILENAME	== to =>	FOLDER                            
	=============================================================================================
		
'''
    #
    #  CHECK LIST ( regular expressions matching filename extension )
    #
    jpg_check = re.compile('.*jpg' , re.IGNORECASE)
    jpeg_check = re.compile('.*jpeg' , re.IGNORECASE)
    png_check = re.compile('.*png' , re.IGNORECASE)
    gif_check = re.compile('.*gif' , re.IGNORECASE)
    js_check = re.compile('.*js' , re.IGNORECASE)
    html_check = re.compile('.*html' , re.IGNORECASE)
    css_check = re.compile('.*css', re.IGNORECASE)
  
    #END CHECK LIST
  
  
    for filename in SITEFILES:
      location1 = FOLDER
      location2 = FOLDER
      location3 = FOLDER
      if jpg_check.match(filename)  or jpeg_check.match(filename)  or png_check.match(filename) or gif_check.match(filename):
        location1 = location1 + "pics/"
        location2 = location2 + "line_table/pics/"
        loaction3 = location3 + "translation_table/pics/"
      elif js_check.match(filename) or html_check.match(filename) or css_check.match(filename):
        #location1
        location2 = location2 + "line_table/"
        loaction3 = location3 + "translation_table/"
      else:
        print "** Unkmown file type! copy location unknown.  Double check this file and it's copy location then add the file type extension to the check list**"
      print "\t\t"+filename+"\t== to =>\t"+location1
      print "\t\t"+filename+"\t== to =>\t"+location2
      print "\t\t"+filename+"\t== to =>\t"+location3
      print "\t============================================================================================="
    for filename in MAINFILES:
      location1 = FOLDER
      location2 = FOLDER
      location3 = FOLDER
      if jpg_check.match(filename)  or jpeg_check.match(filename)  or png_check.match(filename) or gif_check.match(filename):
        location1 = location1 + "pics/"
        location2 = location2 + "line_table/pics/"
        loaction3 = location3 + "translation_table/pics/"
      elif js_check.match(filename) or html_check.match(filename) or css_check.match(filename):
        #location1
        location2 = location2 + "line_table/"
        loaction3 = location3 + "translation_table/"
      else:
        print "** Unkmown file type! copy location unknown.  Double check this file and it's copy location then add the file type extension to the check list**"
      print "\t\t"+filename+"\t== to =>\t"+location1
      print "\t\t"+filename+"\t== to =>\t"+location2
      print "\t\t"+filename+"\t== to =>\t"+location3
      print "\t============================================================================================="     
    print "************************************************************************************************************"
  
if __name__ == '__main__':
  #CORP201MS = xparser.process('data/CORP201.xml')
  #database = manuscript_db()
  #use_key = 'C'
  #print database.get_line_table("D54.01.01")
  #print database.get_one_MS(use_key)
  #for keys in filenames:
  #  filecount += 1
  time1 = time.localtime()
  if len(sys.argv) < 2:
    #print "\tusage: python translator.py --[command]"
    #print "type: python translator.py --help for help"
    print_help()
    sys.exit()

  else:
    if sys.argv[1] == "--all" or sys.argv[1] == "--main" or sys.argv[1] == "--ct" or sys.argv[1] =="--tt": #translate all files
      cmd = sys.argv[1]
      print "Start time: "+time.strftime("%I:%M:%S %p", time1)
      print "Generating pages..."
      #print "DEBUG: " +str(time1)
      #generate files
      if cmd == "--all" or cmd == "--main":
        #file_count += gen_all_MS_paged()
	gen_all_MS_paged()
	gen_one_TRANSLATION_paged()
      if cmd == "--all" or cmd == "--ct":
        file_count += gen_line_table_pages()
	#if cmd == "--ct":
	  #print_warning()
      if cmd == "--all" or cmd =="--tt":
        file_count += gen_translation_table_pages()
	if cmd == "--tt":
	  print_warning()
      if cmd == "--all":
        file_count += copy_site_files()
      print "Done."
      time2 = time.localtime()
      print "Finished at "+ time.strftime("%I:%M:%S %p", time2)
      seconds = (60*(time2[4]-time1[4]))-time1[5]+time2[5]
      minutes = (seconds/60)
      #print "Min: "+str(minutes)
      if minutes > 0:
       seconds = seconds % 60 
      #if time2[4] == time1[4]:
      #  print "Generation took "+str(time2[3] - time1[3])+" hours, "+str(time2[4] - time1[4])+" minute, and "+str(time2[5] - time1[5])+" seconds."
      #else:
    
      print "Generation took "+str(minutes)+" minutes and "+str(seconds)+" seconds."
      
      if cmd == '--main' or cmd == '--ct':
        print_warning()
	
    elif sys.argv[1] == '--ms':
      if len(sys.argv) != 3:
         print "usage: python translator.py --ms <manuscript key>"
	 print "type: python translator.py --help for help"
      else:
        MS_key = sys.argv[2]
	#
	# PRINT START TIME & manuscript
	#
        print "Start time: "+time.strftime("%I:%M:%S %p", time1)
        print "Generating " + str(MS_key) + " to " + FOLDER+ FILENAMES[MS_key] + "..."	
	
        file_count += gen_one_MS(MS_key)
	print "Done."
        time2 = time.localtime()
        print "Finished at "+ time.strftime("%I:%M:%S %p", time2)
        seconds = (60*(time2[4]-time1[4]))-time1[5]+time2[5]
        minutes = (seconds/60)
        #print "Min: "+str(minutes)
        if minutes > 0:
          seconds = seconds % 60 
      #if time2[4] == time1[4]:
      #  print "Generation took "+str(time2[3] - time1[3])+" hours, "+str(time2[4] - time1[4])+" minute, and "+str(time2[5] - time1[5])+" seconds."
      #else:
    
        print "Generation took "+str(minutes)+" minutes and "+str(seconds)+" seconds."
	print_warning()
  
    elif sys.argv[1] == '--trans':

      if len(sys.argv) == 3:
        MS_key = sys.argv[2]
        gen_one_TRANSLATION_paged(MS_key)

      else:
        gen_one_TRANSLATION_paged()
        #print "All translation call here"
      print_warning()
    elif sys.argv[1] == '--help':
      print_help()
      sys.exit()
    elif sys.argv[1] == '--setup':
      print_setup()
      sys.exit()
    elif sys.argv[1] == '--copy':
      file_count = copy_site_files()
    elif sys.argv[1] == '--lpdb':
      get_pg_and_line_no()
    elif sys.argv[1] == '--tlpdb':
      get_pg_and_line_no(translation=True)
    elif sys.argv[1] == '--staticinfo':
      print_warning(True)
    elif sys.argv[1] == '--msp':
      if len(sys.argv) != 3:
        print "usage: python translator.py --ms <manuscript key>"
        print "type: python translator.py --help for help"
      else:
        MS_key = sys.argv[2]
	print "Start time: "+time.strftime("%I:%M:%S %p", time1)
	
	if MS_key.upper() == "ALL":
	  print "Generating multi-page version of ALL Manuscripts!"
	  gen_all_MS_paged()
	else:
	  print "Generating multi-page version of Manuscript "+str(MS_key)
 	  #print "Generating " + str(MS_key) + " to " + FOLDER+ FILENAMES[MS_key] + "..."
          gen_one_MS_paged(MS_key)
	print_warning()  
        print "Done."
        time2 = time.localtime()
        print "Finished at "+ time.strftime("%I:%M:%S %p", time2)
        seconds = (60*(time2[4]-time1[4]))-time1[5]+time2[5]
        minutes = (seconds/60)
        #print "Min: "+str(minutes)
        if minutes > 0:
          seconds = seconds % 60 
      #if time2[4] == time1[4]:
      #  print "Generation took "+str(time2[3] - time1[3])+" hours, "+str(time2[4] - time1[4])+" minute, and "+str(time2[5] - time1[5])+" seconds."
      #else:
    
        print "Generation took "+str(minutes)+" minutes and "+str(seconds)+" seconds."
	#print_warning()
        
    elif sys.argv[1] == '--lm':
      print "= OE PROJECT NON-GENERATED HTML FILES LIST ="
      for filename in MAINFILES:
        if 'html' in filename:
	  print "= "+str(filename)+ " ="
    else:
       print_help()
       sys.exit()
	
    print "Generated a total of "+str(CURRENT_FILE.get_files_written() + file_count)+" files." 

#print citationDict